0

我想创建简单的 Android 蓝牙客户端-服务器程序

服务器代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv1=(TextView)findViewById(R.id.textView1);
    tv2=(TextView)findViewById(R.id.textView2);
    mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
    try {
        mBluetoothServerSocket=mBluetoothAdapter.listenUsingRfcommWithServiceRecord(name,uUID);
        mBluetoothAdapter.cancelDiscovery();
        mBluetoothSocket=mBluetoothServerSocket.accept();
        mInputStream=mBluetoothSocket.getInputStream();
        //if(mInputStream.available()>0){
            mBufferedReader=new BufferedReader(new InputStreamReader(mInputStream));
            data = mBufferedReader.readLine();
            tv1.setText(data);
        //} 
            if(mInputStream.available()>0){
            data=mBufferedReader.readLine();
            tv2.setText(data);
            x++;
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}

客户代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lb=(Button)findViewById(R.id.button1);
    btAdapter = BluetoothAdapter.getDefaultAdapter();

      BluetoothDevice device = btAdapter.getRemoteDevice(addressHTC);
      try {
        btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        btAdapter.cancelDiscovery();
        btSocket.connect();
        String message = "Hello.............. from....... Android......\n";
        outStream = btSocket.getOutputStream();
        byte[] msgBuffer = message.getBytes();
        outStream.write(msgBuffer);
      }
    catch(IOException e){
        e.printStackTrace();    
    }
      lb.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String m1="msg 2";
            byte[] msgBuffer = m1.getBytes();
            try {
                outStream.write(msgBuffer);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
}

此应用程序在一侧模式下工作,只需向服务器发送消息并显示接收到的缓冲区,但我需要不断地从服务器向客户端发送一些消息。

怎么做?

如果你有任何想法。请分享。

4

2 回答 2

0

这对我来说可以持续阅读。试试看。

       try {
            BufferedReader Reader = new BufferedReader(
                    new InputStreamReader(mmSocket.getInputStream()));

            while(true)
            {                   
                String receivedMsg;
                while((receivedMsg = Reader.readLine()) != null)
                {
                     // what you do with your message 
                }

            }
        } catch (Exception ex) {
            System.out.println(ex);
        }
于 2013-10-08T11:07:06.953 回答
0

你应该有一个不同的线程来监听,它将消息发送到活动,这个线程也可以是发送消息的线程。这样你的用户界面就不会卡住,你可以连续接收消息。这种线程的一个例子:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.util.Log;

public class MessageManager extends Thread {

private static final String TAG = "MessageListener thread";
private BluetoothSocket btConnectedSocket;
private InputStream inStream;
private OutputStream outStream;
private Activity parent;
private boolean run = true;

public MessageManager(BluetoothSocket btConnectedSocket, Activity parent) throws IOException {
    this.btConnectedSocket = btConnectedSocket;
    this.parent = parent;
    inStream =  btConnectedSocket.getInputStream();
    outStream = btConnectedSocket.getOutputStream();        
}

/* this method will listen continuously to messages received through the BT socket until you call cancel
public void run() {
    byte[] buffer = new byte[1024];
    int bytes; 

    while (run) {
        try {
            bytes = inStream.read(buffer);
        }
        catch(IOException ex) {
            Log.e(TAG, "error while reading from bt socket");

        }
        parent.doStuffWithTheMessage(buffer); // pay attention: its in bytes. u need to convert it to a string
    }
}

/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) throws IOException{
        outStream.write(bytes);
}

/* Call this from the main activity to shutdown the connection */
public void cancel() {
    run = false;
    try {
        btConnectedSocket.close();
    } catch (IOException e) { }

}

}

于 2013-10-13T23:57:29.363 回答