我正在尝试在屏幕关闭时保持蓝牙连接。所以我创建了一个应用程序,你可以发现周围的蓝牙设备,并从列表中选择。然后将选择的蓝牙设备传递给后台服务类,后者将处理其余部分。但是当我尝试从意图中获取设备时,我得到空指针。任何帮助将不胜感激。
这是我的代码段
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if(btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if(listAdapter.getItem(arg2).contains("Paired")){
BluetoothDevice selectedDevice = devices.get(arg2);
Intent intent = new Intent(this,backgroundService.class);
if(selectedDevice == null)
Log.i(backgroundService.EXTRA_MESSAGE, "I am telling you it is null");
intent.putExtra(backgroundService.EXTRA_MESSAGE, (Parcelable)selectedDevice);
startService(intent);
}
else{
Toast.makeText(getApplicationContext(), "device is not paired", 0).show();
}
}
我还按以下方式填充设备
receiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_FOUND)){
Log.i("onReceive", "ACTION_FOUND");
BluetoothDevice d = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String s = "Not Paired";
devices.add(d);
for(int a = 0; a < pairedDevices.size(); a++){
if(d.getName().equals(pairedDevices.get(a).getName())){
//append
s = "Paired";
break;
}
}
listAdapter.add(d.getName()+"("+s+")\n"+ d.getAddress());
}
因此,设备列表必须已具有可分配的设备。我从以下代码获取null设备
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(EXTRA_MESSAGE,"onStartCommand");
BluetoothDevice selectedDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(selectedDevice == null)
{Log.i(EXTRA_MESSAGE,"null it is "); return -1;}
connect = new ConnectThread(selectedDevice);
connect.start();
答案 0 :(得分:3)
改变这个:
BluetoothDevice selectedDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
对此:
BluetoothDevice selectedDevice = intent.getParcelableExtra(EXTRA_MESSAGE);