Android蓝牙客户端服务器连接

时间:2013-10-07 10:44:17

标签: android android-bluetooth

我想创建简单的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();
            }

        }
    });
}

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

怎么做?

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

2 个答案:

答案 0 :(得分: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);
        }

答案 1 :(得分:0)

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

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) { }

}

}