web-dev-qa-db-ja.com

BluetoothAdapterに加えられた状態変更を検出しますか?

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の状態を反転させ、次にUIを更新するButtonTextを呼び出します。ただし、私が抱えている問題は、BTがオンになるのに数秒かかることです。これらの秒の間、BTステータスが有効にならず、ボタンが2秒以内にオンになってもBluetoothがオフになります。

STATE_CONNECTING BluetoothAdapterの定数Androidドキュメンテーション、しかし...私は単純にそれを使用する方法がわからない。

だから、私は2つの質問があります:

  1. UI要素(ボタンや画像など)をBT状態に動的に結び付ける方法はありますか。BT状態が変化すると、ボタンも変化しますか?
  2. それ以外の場合は、ボタンを押して正しい状態を取得します(2秒以内にオンになるので、接続している場合でもBTをオンにしたいです)。どうすればいいですか?
67
raingod

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;
            }
        }
    }
};
_

これは、ActivityButtonのテキストを適宜変更するメソッドsetButtonText(String text)を実装することを前提としていることに注意してください。

そして、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);
}
_
179
Alex Lockwood