检测对蓝牙适配器进行的状态更改?

我有一个应用程序,上面有一个按钮,我用它来打开和关闭 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常量,但是... ... 作为一个新手,我根本不知道如何使用它。

我有两个问题:

  1. 有没有一种方法可以动态地将 UI 元素(例如按钮或图像)绑定到 BT 状态,这样当 BT 状态改变时,按钮也会改变?
  2. 否则,我想按下按钮,并得到正确的状态(我希望它说 BT 的,即使它只是连接,因为它将在2秒钟打开)。我该怎么做?
59113 次浏览

您需要注册一个 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);
}
public void discoverBluetoothDevices(View view)
{
if (bluetoothAdapter!=null)


bluetoothAdapter.startDiscovery();
Toast.makeText(this,"Start Discovery"+bluetoothAdapter.startDiscovery(),Toast.LENGTH_SHORT).show();
}