开发者

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 A开发者_Go百科pplication", 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.


Have you tried using a Bundle?

Check relevant topic

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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜