实际开发过程中需要通过对蓝牙状态的监听以满足需求,这里对蓝牙状态的改变进行了一次封装。
这里运用了动态广播注册,优点是注册取消可以由代码控制,在用到的地方注册,用不到的地方及时取消,避免对手机资源的浪费。
广播接收器BlueToothStateReceiver类
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* 广播监听蓝牙状态
*/
public class BlueToothStateReceiver extends BroadcastReceiver {
public static int DEFAULT_VALUE_BULUETOOTH = 1000;
public OnBlueToothStateListener onBlueToothStateListener;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, DEFAULT_VALUE_BULUETOOTH);
switch (state) {
case BluetoothAdapter.STATE_OFF://蓝牙已关闭
onB