我正在尝试使用蓝牙创建服务器和客户端。 我的想法是服务器应用程序通过蓝牙向客户端应用程序发送消息。 我正在同一智能手机上测试这两款应用。 不幸的是,我无法使其发挥作用。
客户端:
public class MainActivity extends AppCompatActivity {
TextView tv1,tv2;
BluetoothAdapter mBluetoothAdapter;
BluetoothServerSocket mBluetoothServerSocket;
InputStream mInputStream;
BluetoothSocket mBluetoothSocket;
BufferedReader mBufferedReader;
String data;
UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
@Override
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("Service Name",MY_UUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket=mBluetoothServerSocket.accept();
mInputStream=mBluetoothSocket.getInputStream();
if(mInputStream.available()>0){
data=mBufferedReader.readLine();
tv2.setText(data);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
服务器:
public class Main2Activity extends AppCompatActivity {
private BluetoothAdapter btAdapter;
private Button lb;
private BluetoothDevice device;
private BluetoothSocket btSocket;
private OutputStream outStream;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lb=(Button)findViewById(R.id.button1);
btAdapter = BluetoothAdapter.getDefaultAdapter();
UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice device = btAdapter.getRemoteDevice("00:03:AB:59:19:C3");
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btAdapter.cancelDiscovery();
btSocket.connect();
String message = "Message\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();
}
}
});
}
}
感谢。