Android 判断蓝牙是否开启,监听蓝牙状态,处理客制化需求

import android.bluetooth.BluetoothAdapter;

【BluetoothAdapter.java】

@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)

public static final String
ACTION_STATE_CHANGED = "android.bluetooth.adapter.action.STATE_CHANGED";//当前action动作

/**

* Used as an int extra field in {@link #ACTION_STATE_CHANGED}

* intents to request the current power state. Possible values are:

* {@link #STATE_OFF},

* {@link #STATE_TURNING_ON},

* {@link #STATE_ON},

* {@link #STATE_TURNING_OFF},

*/

//intent.getIntExtra 参数
public static final String EXTRA_STATE = "android.bluetooth.adapter.extra.STATE";//当前状态

public static final String EXTRA_PREVIOUS_STATE =
"android.bluetooth.adapter.extra.PREVIOUS_STATE";//上一个状态

public static final int STATE_OFF = 10;

public static final int STATE_TURNING_ON = 11;

public static final int STATE_ON = 12;

public static final int STATE_TURNING_OFF = 13;

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

boolean bluetoothEnable = bluetoothAdapter == null ? false : bluetoothAdapter.isEnabled();

if (bluetoothEnable) {//判断蓝牙是否开启

//处理逻辑

}

监听蓝牙广播:

IntentFilter bt = new IntentFilter();

bt.addAction(BluetoothAdapter.ACTION_STATE_CHANGED );

mContext.registerReceiver(mReceiver, bt);
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

@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, BluetoothAdapter.ERROR);//监听当前蓝牙状态

switch (state) {

case BluetoothAdapter.STATE_OFF:
//添加其他处理逻辑,比如亮灭led灯,密码弹窗,控制可用禁用等
break;
case BluetoothAdapter.STATE_ON:
//添加其他处理逻辑
break;

case BluetoothAdapter.STATE_TURNING_OFF:

break;

case BluetoothAdapter.STATE_TURNING_ON:

break;

}

}

}

};

最好的监听地方是状态栏上:

/vendor/mediatek/proprietary/packages/apps/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java 的start()方法里面注册广播

其实,对应如此,NFC也可以这样!NfcAdapter

相关推荐
nameofworld3 分钟前
前端面试笔试(五)
开发语言·前端·javascript·面试·递归
zybishe4 分钟前
计算机毕业设计原创定制(免费送源码)Java+SpringBoot+MySQL SpringBoot物流配送后台系统
java·css·c++·spring boot·spark·django·课程设计
BIM云平台开发6 分钟前
关于return,yield 和 yield return
java·开发语言·数据结构·c#
小柯J桑_7 分钟前
C++:用红黑树封装map与set-2
开发语言·c++·set·map·红黑树
GGBondlctrl14 分钟前
【Spring MVC】关于Spring MVC编程中与http请求的参数传递的详细介绍
java·spring·mvc·postman·请求参数的传递·json的传递
小小unicorn16 分钟前
基于Boost库的搜索引擎
java·搜索引擎·dubbo
m0_7482329216 分钟前
JVM的内存区域划分
java·jvm·算法
zwm_yy19 分钟前
Dockerfile && docker-compose
开发语言·docker
遇见你真好。23 分钟前
x-easypdf 初始与简单使用
java·springboot·x-easypdf
菜鸟挣扎史26 分钟前
关于一次开源java spring快速开发平台项目RuoYi部署的记录
java·spring·开源