检测对BluetoothAdapter所做的状态更改?

rai*_*god 67 java android bluetooth

我有一个带有按钮的应用程序,用于打开和关闭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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在调用按钮Flip,它会翻转BT状态,然后调用ButtonText,它应该更新UI.但是,我遇到的问题是,BT打开需要几秒钟 - 在这几秒钟内,BT状态未启用,使我的按钮说蓝牙关闭,即使它将在2秒内打开.

STATE_CONNECTING在BluetoothAdapter android文档中找到了常量,但是......我根本就不知道如何使用它,成为一个新手和所有.

所以,我有两个问题:

  1. 有没有办法动态地将UI元素(如按钮或图像)绑定到BT状态,这样当BT状态改变时,按钮也会改变?
  2. 否则,我想按下按钮并获得正确的状态(我希望它说BT,即使它只是连接,因为它将在2秒内开启).我该怎么做呢?

Ale*_*ood 184

您将要注册一个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;
            }
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

请注意,这假设您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);
}
Run Code Online (Sandbox Code Playgroud)

  • 您应该在onStart和onStop中注册和注销.onDestroy不保证被调用! (8认同)