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

相关推荐
fire-flyer27 分钟前
Spring Boot 源码解析之 Logging
java·spring boot·spring·log4j·logging
papership33 分钟前
【入门级-C++程序设计:12、文件及基本读写-文件的基本概念&文本文件的基本操作】
开发语言·c++·青少年编程
SaleCoder2 小时前
用Python构建机器学习模型预测股票趋势:从数据到部署的实战指南
开发语言·python·机器学习·python股票预测·lstm股票模型·机器学习股票趋势
KoiHeng2 小时前
部分排序算法的Java模拟实现(复习向,非0基础)
java·算法·排序算法
cui_hao_nan5 小时前
JVM——如何对java的垃圾回收机制调优?
java·jvm
熟悉的新风景7 小时前
springboot项目或其他项目使用@Test测试项目接口配置-spring-boot-starter-test
java·spring boot·后端
心平愈三千疾7 小时前
学习秒杀系统-实现秒杀功能(商品列表,商品详情,基本秒杀功能实现,订单详情)
java·分布式·学习
玩代码7 小时前
备忘录设计模式
java·开发语言·设计模式·备忘录设计模式
BUTCHER57 小时前
Docker镜像使用
java·docker·容器
岁忧8 小时前
(nice!!!)(LeetCode 面试经典 150 题 ) 30. 串联所有单词的子串 (哈希表+字符串+滑动窗口)
java·c++·leetcode·面试·go·散列表