Programing

BluetoothAdapter의 상태 변경을 감지합니까?

lottogame 2020. 11. 10. 07:41
반응형

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();
    }
}

BT 상태를 뒤집는 Button Flip을 호출 한 다음 UI를 업데이트해야하는 ButtonText를 호출합니다. 그러나 내가 가진 문제는 BT가 켜지는 데 몇 초가 걸리고이 초 동안 BT 상태가 활성화되지 않아 2 초 안에 켜질지라도 내 버튼이 Bluetooth를 끄는 것으로 표시된다는 것입니다.

나는 STATE_CONNECTINGBluetoothAdapter 안드로이드 문서에서 상수를 찾았 지만 ... 나는 그것을 사용하는 방법을 모른다.

그래서 두 가지 질문이 있습니다.

  1. UI 요소 (예 : 버튼 또는 이미지)를 BT 상태에 동적으로 연결하여 BT 상태가 변경 될 때 버튼도 변경되도록하는 방법이 있습니까?
  2. 그렇지 않으면 버튼을 눌러 올바른 상태를 얻고 싶을 것입니다 (연결 중일지라도 2 초 후에 켜질 것이므로 BT on이라고 말하고 싶습니다). 어떻게해야합니까?

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

참고 URL : https://stackoverflow.com/questions/9693755/detecting-state-changes-made-to-the-bluetoothadapter

반응형