我正在尝试在android studio上开发两个应用程序,每个应用程序都运行在不同的Android设备上。我想用蓝牙在这两者之间交换数据。我已经按照Android Developer文档进行了以下操作:搜索设备,建立RFCOMM频道,连接两个设备。但是,我看不到发送或接收的数据。一个应用程序是启动连接的客户端,另一个应用程序是客户端和服务器端。连接后,我使用Handler从流中写入/读取。这是处理程序代码。对于connectedThread
和ConnectThread
,我使用了与Android Developer示例中相同的内容。但是,我不确定何时同时调用read()
和write()
方法,并且通常会存储两个连接设备之间交换的消息?
Handler mhandler = new Handler(){
@Override
public void handleMessage(Message msg){
super.handleMessage(msg);
Log.i(tag, "in handler");
String s = myapplication.getMessage();
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
connectedThread.run();
switch (msg.what){
case SUCCESS_CONNECT:
//ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_LONG).show();
break;
case MESSAGE_WRITE:
connectedThread.write(s.getBytes());
break;
case MESSAGE_READ:
byte[] readbuf = (byte[])msg.obj;
String string = new String(readbuf);
Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
break;
}
}
};