Android:如何将蓝牙连接传递给另一个活动? [英] Android: How to pass a Bluetooth connection to another Activity?
问题描述
我有我的第一个活动,其中建立了 BT 连接.有一个选项会呈现给用户,并且会根据他们的选择加载不同的 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.
问题是,这两个活动都需要一个 BT 连接,我不认为为了建立另一个连接而破坏一个连接有什么意义.
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?
我试过class MyApplication extends Application
",但后来我不能使用:
I've tried "class MyApplication extends Application
", but then I can't use:
super.onCreate(savedInstanceState);
setContentView(R.layout.blablabla);
这可能是一个非常愚蠢的问题,但我只在 Android +- 2 周内.
This may be a pretty silly question but I've only been at Android +- 2 weeks.
推荐答案
您是否尝试过使用 Application 对象将蓝牙连接存储在一个对象中并使用您的活动来获取它?
Have you tried using the Application object to store the Bluetooth connection in an object and using your Activities to get it?
尝试这样的事情.(注意:我从来没有在 Android 上使用过蓝牙,所以我不知道要使用哪些相关的类.在这种情况下,我将使用 BluetoothDevice
,因为它似乎是基于正确的类关于图书馆文档)
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;
}
}
这样,您的第一个 Activity 只需执行以下操作:
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();
...
}
...
}
然后,任何时候您的其他活动需要使用该连接,它们只需要调用 getBtDevice()
,因为 FirstActivity
已经实例化了它.
And then, any time your other Activities need to use that connection, they just need to call getBtDevice()
, because FirstActivity
already instantiated it.
这篇关于Android:如何将蓝牙连接传递给另一个活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!