Bluetooth connection from phone to Bluno disconnects when app goes to another activity

120 Views Asked by At

My goal is to connect my app to a Bluno module. I used and tweaked the codes from this tutorial. Basically my version's launcher activity has a "SCAN" button that lets me scan and connect to the Bluno module. Once connected, it redirects to another activity (which is kind of like the "main" one in a sense that the features are here i.e. chatting, contacts, calls). Problem is, once I've successfully connected and redirected to the other activity, the Bluetooth connection disconnects. How do I fix this? Thank you.

1

There are 1 best solutions below

0
On

Looking at the library example, the problem is probably that if you just copied it straight up then going to the different activity will pause as the BlunoLibrary is written to be an activity class that you extend. Frankly it is a little bizarre - and as an example it is not very helpful for practical use if you intend to have multiple activities or for some reason can't subclass from that, it's also straight up designed to not run in background.

Specifically if you look at

public void onPauseProcess() {
        System.out.println("BLUNOActivity onPause");
        scanLeDevice(false);
        mainContext.unregisterReceiver(mGattUpdateReceiver);
        mLeDeviceListAdapter.clear();
        mConnectionState=connectionStateEnum.isToScan;
        onConectionStateChange(mConnectionState);
        mScanDeviceDialog.dismiss();
        if(mBluetoothLeService!=null)
        {
            mBluetoothLeService.disconnect();
            mHandler.postDelayed(mDisonnectingOverTimeRunnable, 10000);

//          mBluetoothLeService.close();
        }
        mSCharacteristic=null;

}

in BlunoLibrary(or the onDestroy, or the onStop) you'll see that it disconnects the service when you switch activity. you could just not call this(from mainactivity), but then you would need to pass that old activity to the new activity object or at least somehow inform the old one where to send incoming messages. Frankly you would be better off just looking from the BlunoLibrary.java what it actually does(to make the bluetooth connection) and making your own based on that information and then you can make it into a service or however you want so that it survives switching of the activity.