1. 程式人生 > >android藍芽開啟關閉過程監聽

android藍芽開啟關閉過程監聽

在開啟藍芽時,一般藍芽的開啟都需要一個過程,而且有些機型還會開啟失敗,所以就要監測藍芽的開啟過程,下面給出程式碼:

建立一個BluetoothListenerReceiver.
public class BluetoothListenerReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        switch (intent.getAction()) {
            case BluetoothAdapter.ACTION_STATE_CHANGED:
                int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                switch (blueState) {
                    case BluetoothAdapter.STATE_TURNING_ON:
                        Log.e("onReceive---------藍芽正在開啟中");
                     
                        break;
                    case BluetoothAdapter.STATE_ON:
                        Log.e("onReceive---------藍芽已經開啟");
                  
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        Log.e("onReceive---------藍芽正在關閉中");
                    
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        Log.e("onReceive---------藍芽已經關閉");
                      
                        break;
                }
                break;
        }

    }
}

在activity或者fragment中註冊receiver

private BluetoothListenerReceiver receiver;
@Override
public void onCreate(@Nullable Bundle savedInstanceState, Context mContext) {
  receiver = new BluetoothListenerReceiver(); 
  mContext.registerReceiver(receiver,makeFilter());
}
private IntentFilter makeFilter() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    return filter;
}

這樣就可以監聽藍芽的開啟和關閉過程了。