Android: How to pass a Bluetooth connection to another Activity?

后端 未结 4 1321
暗喜
暗喜 2021-01-03 07:31

I have my first Activity in which the BT connection is established. There is an option presented to the user and, based on their selection, a different Activity will load.

4条回答
  •  再見小時候
    2021-01-03 07:47

    Have you tried using the Application object to store the Bluetooth connection in an object and using your Activities to get it?

    Try something like this. (Note: I have never worked with Bluetooth on Android, so I don't know which relevant classes to use. In this case, I'll use BluetoothDevice, since it seems to be the right class based on the library documentation)

    public class MyApplication extends Application {
        BluetoothDevice device;
        ...
        public synchronized BluetoothDevice getBtConnection() {
            if (device == null) {
                // construct a BluetoothDevice object and put it into variable device
            }
            return device;
        }
    }
    

    That way, your first activity just has to do this:

    public class FirstActivity extends Activity {
        private BluetoothDevice device;
        ...
        @Override
        protected void onCreate(Bundle b) {
            super(b);
            ...
            device = ((MyApplication) getApplication()).getBtDevice();
            ...
        }
        ...
    }
    

    And then, any time your other Activities need to use that connection, they just need to call getBtDevice(), because FirstActivity already instantiated it.

提交回复
热议问题