在打开蓝牙时,一般蓝牙的打开都需要一个过程,而且有些机型还会打开失败,所以就要监测蓝牙的打开过程,下面给出代码:
创建一个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; }
这样就可以监听蓝牙的打开和关闭过程了。