我有一个应用程序,上面有一个按钮,用于打开和关闭 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 秒内打开。
我在 BluetoothAdapter android 文档中找到了 STATE_CONNECTING
常量,但是……作为一个新手,我根本不知道如何使用它。
所以,我有两个问题:
- 有没有办法将 UI 元素(如按钮或图像)动态绑定(bind)到 BT 状态,这样当 BT 状态改变时,按钮也会随之改变?
- 否则,我想按下按钮并获得正确的状态(我想让它说 BT 开启,即使它只是连接,因为它会在 2 秒内开启)。我该怎么做?
最佳答案
您需要注册一个 BroadcastReceiver
来监听 BluetoothAdapter
状态的任何变化:
作为您的 Activity
中的私有(private)实例变量(或在单独的类文件中......无论您喜欢哪个):
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);
}
关于java - 检测对蓝牙适配器所做的状态更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9693755/