我找到了一个用于管理服务连接的示例代码。但我不知道如何使用它。
我只在这里写下我不理解的代码,以查看所有代码:
CODE
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("popopo", "Onstart Command");
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
deviceName = device.getName();
String macAddress = device.getAddress();
if (macAddress != null && macAddress.length() > 0) {
connectToDevice(macAddress);
} else {
stopSelf();
return 0;
}
}
String stopservice = intent.getStringExtra("stopservice");
if (stopservice != null && stopservice.length() > 0) {
stop();
}
return START_STICKY;
}
我在没有服务的情况下正确连接到蓝牙,使用此代码获取设备:
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
我的问题是:onStartCommand()
执行时如何传递我找到的蓝牙设备ID?
当我没有执行ACTION_FOUND时,它尝试连接哪个蓝牙设备?
答案 0 :(得分:0)
可能有点晚了,但为了以防万一。如果我没记错的话,有多种方法可以连接到设备,因为它的mac地址。
将设备的地址作为创建意图中的额外地址传递。
在UI活动中
Intent intent=new Intent(this,BluetoothService.class));
intent.putExtra("DEVICE_ADDRESS",device.getAddress());
startService(intent);
在蓝牙服务中
public int onStartCommand(Intent intent, int flags, int startId) {
String address = intent.getExtras("DEVICE_ADDRESS");
###DO SOMETHING WITH ADDRESS HERE###
}
创建一个' connectToDevice(字符串地址)'您服务中的方法,并从您拥有BroadcastReceiver的任何地方进行调用。
在蓝牙服务中
protected synchronized void connectToDevice(BluetoothDevice device){//Cancells any threads attempting to connect and starts a new connectThread (new connection)
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
Log.d(TAG,"Cancelled connectThread");
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
Log.d(TAG,"Cancelled connectedThread");
}
mConnectThread = new ConnectThread(device);
mConnectThread.start();
Log.d(TAG,"Starting connectThread");
}
在广播接收器中
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BluetoothService mBluetoothService = new BluetoothService();
mBluetoothService.connectToDevice(device.getAddress());
}
你应该查看android提供的BluetoothChat example。我认为它显示了你需要的很多东西。