I am using Bluetooth in my app to connect with a thermal printer. First I check if Bluetooth is enabled or not and everything is fine. But I am facing a problem when I close Bluetooth while in app or not. My app crashes with a null pointer exception which is not handled in the BluetoothService
class.
Also, I have notice that even if I am not in my app and I close the Bluetooth it calls my app and shows me a toast message from my code.
dose anyone faced this problem?
here is the null pointer exception from bluetooth server socket
03-03 17:13:27.576 9916-10431/co.lvlz.skiplino.provider E/AndroidRuntime: FATAL EXCEPTION: AcceptThread Process: co.lvlz.skiplino.provider, PID: 9916
java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.BluetoothSocket
android.bluetooth.BluetoothServerSocket.accept()' on a null object reference at com.zj.btsdk.BluetoothService$AcceptThread.run(BluetoothService.java:316)
here Bluetooth is handled and how I destroy the activity
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
break;
case BluetoothService.STATE_CONNECTING:
Log.d("��������","��������.....");
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Toast.makeText(getApplicationContext(), "bluetooth is closed",
Toast.LENGTH_SHORT).show();
Log.d("None", "stateNone");
MainActivity.this.finish();
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST:
Log.d("None", "connection lost to device");
Toast.makeText(getApplicationContext(),"Connetion was lost to device",
Toast.LENGTH_SHORT).show();
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT:
Toast.makeText(getApplicationContext(), "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
protected void onDestroy() {
super.onDestroy();
if (mService != null)
{
Log.d("None", "nullMe");
activitydestroyed=true;
mService.stop();
}
else {
Log.d("None", "nullMe2");
mService = null;
}
}