notification if the Bluetooth is turned off in android app

前端 未结 2 1240
甜味超标
甜味超标 2021-02-04 05:06

Im currently working on a android application.. I have to notify the user whenever the bluetooth of the device is turned off while the application is currently running.. How

相关标签:
2条回答
  • 2021-02-04 05:14

    Register BroadcastReceiver with intent action BluetoothAdapter.ACTION_STATE_CHANGED and move your notifiyng code into onReceive method. Don't forget to check if new state is OFF

    if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
        if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) 
            == BluetoothAdapter.STATE_OFF)
            // Bluetooth was disconnected
    }
    
    0 讨论(0)
  • 2021-02-04 05:14

    If you want to detect when the user is DISCONNECTING his Bluetooth, and later, detect when the user has his Bluetooth DISCONNECTED, you should do the following steps:

    1) Get the user BluetoothAdapter:

    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();    
    

    2) Create and configure your Receiver, with a code as this:

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
            String action = intent.getAction();
    
            // It means the user has changed his bluetooth state.
            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
    
                if (btAdapter.getState() == BluetoothAdapter.STATE_TURNING_OFF) {
                    // The user bluetooth is turning off yet, but it is not disabled yet.
                    return;
                }
    
                if (btAdapter.getState() == BluetoothAdapter.STATE_OFF) {
                    // The user bluetooth is already disabled.
                    return;
                }
    
            }
        }
    };    
    

    3) Register your BroadcastReceiver into your Activity:

    this.registerReceiver(mReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));    
    
    0 讨论(0)
提交回复
热议问题