简体   繁体   中英

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

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.

The problem is, both activities need a BT connection and I don't see the point in destroying one connection just to make another.

Is there a way that I could pass the connection between Activities?

Does anyone have some example for me or perhaps a link?

I've tried " class MyApplication extends Application ", but then I can't use:

super.onCreate(savedInstanceState);
setContentView(R.layout.blablabla);

This may be a pretty silly question but I've only been at Android +- 2 weeks.

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.

I know it's an old question, but for the new people visiting this topic:

I think Kibibyte's answer would also work, but otherwise there is the option to use a (Bound)Service . This would run even if the app closes

Official Android Service documentation

Have you tried using a Bundle?

Check relevant topic

http://www.anddev.org/putting_an_object_into_a_bundle-t6431.html

i had same problem ,and finally solve it! so at first you should create your connection in an activity and be sure that the connection store in public static variable and you can call that connection variable in each activity that you want to have Bluetooth Connection. I suggest you to use service class to create connection and use connection variable like this

BluetoothChatService mChatService=DeviceListActivity.chatService

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM