Your mmDevice
is not instantiated properly, that's why you're getting NullPointerException
. Prevent this with simple nullcheck: if(mmDevice!=null)
.
- Do you ask for permissions at runtime? Since Android M, you should check for permissions from your Activity:
private void checkPermissions() {
ArrayList<String> permissions = ArrayList();
if (checkSelfPermission(applicationContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
permissions.add(ACCESS_FINE_LOCATION);
if (checkSelfPermission(applicationContext, BLUETOOTH) != PackageManager.PERMISSION_GRANTED)
permissions.add(BLUETOOTH);
if (checkSelfPermission(applicationContext, BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED)
permissions.add(BLUETOOTH_ADMIN);
if (permissions.isNotEmpty())
requestPermissions(permissions.toTypedArray(), REQUEST_PERMISSIONS);
else {
startBluetoothService();
}
}
- Make sure you instantiate your BluetoothDevice object properly. For that, you should either scan for devices using BluetoothManager:
BluetoothManager mBluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mBluetoothAdapter = mBluetoothManager.adapter;
//check if bluetooth is enabled
if (mBluetoothAdapter.isEnabled){
mBluetoothAdapter.startDiscovery();
//make sure you register this receiver to properly receive callbacks
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
doThingsWithDevice();
}
}
}
};
or, if you know device address
, you can use mBluetoothManager.adapter.getRemoteDevice("deviceAddress")
method.