I am trying to maintain bluetooth connection when the screen is off. So I created an app that you can discover bluetooth devices around and choose from list. Then pass the chosen bluetooth device to backgroundService class which will handle the rest.But I am getting null pointer when I try to get device from intent. Any help will be appreciated.
Here is my code segments
@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();
}
}
I also populate devices as follows
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());
}
So devices list must already have parcelable devices. I am getting null device from following code
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();