我有一个带有按钮的应用程序,我用它来打开和关闭 BT。我在那里有以下代码;
public void buttonFlip(View view) {
flipBT();
buttonText(view);
}
public void buttonText(View view) {
Button buttonText = (Button) findViewById(R.id.button1);
if (mBluetoothAdapter.isEnabled() || (mBluetoothAdapter.a)) {
buttonText.setText(R.string.bluetooth_on);
} else {
buttonText.setText(R.string.bluetooth_off);
}
}
private void flipBT() {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
} else {
mBluetoothAdapter.enable();
}
}
我正在调用按钮 Flip,它会翻转 BT 状态,然后调用 ButtonText,它应该更新 UI。然而,我遇到的问题是,BT 需要几秒钟才能打开 - 在这几秒钟内,BT 状态未启用,使我的按钮显示蓝牙关闭,即使它会在 2 秒后打开。
我找到了STATE_CONNECTING
蓝牙适配器 android 文档中的常量,但是...我只是不知道如何使用它,作为一个新手等等。
所以,我有两个问题:
- 有没有一种方法可以将 UI 元素(例如按钮或图像)动态绑定到 BT 状态,以便当 BT 状态发生变化时,按钮也会发生变化?
- 否则,我想按下按钮并获得正确的状态(我想让它说 BT 打开,即使它只是连接,因为它会在 2 秒内打开)。我该怎么做呢?
您将需要注册一个BroadcastReceiver
监听状态的任何变化BluetoothAdapter
:
作为您的私有实例变量Activity
(或者在一个单独的类文件中......无论您喜欢哪一个):
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
setButtonText("Bluetooth off");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
setButtonText("Turning Bluetooth off...");
break;
case BluetoothAdapter.STATE_ON:
setButtonText("Bluetooth on");
break;
case BluetoothAdapter.STATE_TURNING_ON:
setButtonText("Turning Bluetooth on...");
break;
}
}
}
};
请注意,这假设您的Activity
实现一个方法setButtonText(String text)
这将改变Button
相应的文本。
然后在你的Activity
,注册和注销BroadcastReceiver
如下,
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* ... */
// Register for broadcasts on BluetoothAdapter state change
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, filter);
}
@Override
public void onDestroy() {
super.onDestroy();
/* ... */
// Unregister broadcast listeners
unregisterReceiver(mReceiver);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)