Detecting state changes made to the BluetoothAdapter?

前端 未结 2 552
不思量自难忘°
不思量自难忘° 2020-11-27 12:33

I have an app with a button on it that I use to turn BT on and off. I have the following code in there;

public void buttonFlip(View view) {
    flipBT();
            


        
相关标签:
2条回答
  • 2020-11-27 12:39
    public void discoverBluetoothDevices(View view)
        {
            if (bluetoothAdapter!=null)
    
                bluetoothAdapter.startDiscovery();
                Toast.makeText(this,"Start Discovery"+bluetoothAdapter.startDiscovery(),Toast.LENGTH_SHORT).show();
        }
    
    0 讨论(0)
  • 2020-11-27 12:46

    You will want to register a BroadcastReceiver to listen for any changes in the state of the BluetoothAdapter:

    As a private instance variable in your Activity (or in a separate class file... whichever one you prefer):

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

    Note that this assumes that your Activity implements a method setButtonText(String text) that will change the Button's text accordingly.

    And then in your Activity, register and unregister the BroadcastReceiver as follows,

    @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);
    }
    
    0 讨论(0)
提交回复
热议问题