通过intent在两个Activity中传递macAdress,但是在第二个页面无法建立与蓝牙的连接。
private BluetoothAdapter bluetoothAdapter;
public BluetoothSocket mSocket;
private BroadcastReceiver receiver;
private final int CONNECTED = 1000;
private final int DISCONNECTED = 1001;
private int state = DISCONNECTED;
private ComThread mThread = null;
//private ConnectThread mThread = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_control);
init();
bind();
bluetoothOpen();
}
private void bluetoothOpen() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Intent intent = this.getIntent();
String macAdress = intent.getStringExtra("macAdress");
Toast.makeText(getApplicationContext(), macAdress, Toast.LENGTH_SHORT).show();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(macAdress);
try
{
/*
final String SPP_UUID="";
UUID uuid = UUID.fromString(SPP_UUID); //Standard SerialPortService ID
mSocket = device.createRfcommSocketToServiceRecord(uuid);
*/
Method clientMethod = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
mSocket = (BluetoothSocket) clientMethod.invoke(device, 1);
// 1 连接单片机 , 2和3 连接手机
try
{
mSocket.connect();//连
if (mSocket.isConnected())
{
Toast.makeText(getApplicationContext(), "蓝牙连接成功", Toast.LENGTH_SHORT).show();
mThread = new ComThread(mSocket);
mThread.start();//另开一个线程,与蓝牙设备进行通信
state = CONNECTED;
}
else
{
Toast.makeText(getApplicationContext(), "蓝牙连接失败", Toast.LENGTH_SHORT).show();
mSocket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
有没有报错信息,输出连接蓝牙相关参数是否有误。
第二个页面无法建立与蓝牙的连接? 第一个页面可以连接的话,那就是蓝牙端口被占用了导致第二个页面无法链接