0

I have an app used for Bluetooth control of an embedded system using the SPP protocol that has worked fine until Marshmallow. If Bluetooth is enabled when I start the app everything is good. I use startActivityForResult() to prompt the user to allow Bluetooth to be enabled if it's not already. It used to block until a result was given but under Marshmallow it blows through it and crashes immediately with a null pointer exception. I added a "hack" in onResume() to keep it from doing this by returning if not enabled, but am wondering if this is poor practice?

  @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    btAdapter = BluetoothAdapter.getDefaultAdapter();

    if (btAdapter == null) {
        Toast.makeText(getApplicationContext(), "No bluetooth detected", Toast.LENGTH_SHORT).show();
        finish();
    } else {
        if (!btAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, ENABLE_BT_REQUEST_CODE);                

        }
    }
}


@Override
public void onResume() {
    super.onResume();       


    /* This keeps from crashing immediately if BT not enabled */
    if (!btAdapter.isEnabled()) {
        return;
    };

    if (btAdapter.isDiscovering()) {
        btAdapter.cancelDiscovery();
    }

    // Rest of code .......
}



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // Check Result from turnOnBT()
    if (requestCode == ENABLE_BT_REQUEST_CODE) {

        if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
            finish();
        }

    }

}
john8791
  • 161
  • 1
  • 2
  • 10
  • I remember there is some bug with SPP in Android 6.0 , I would surround the code such that it only gets executed in Android 6.0 – Amrit kumar Jun 21 '18 at 01:23
  • 1
    I have done some Google searching and unfortunately haven't found a reported bug specific to my problem. – john8791 Jun 21 '18 at 12:56

0 Answers0