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

相关推荐
Dontla7 分钟前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen7 分钟前
python rest请求、requests
开发语言·python
铁东博客13 分钟前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang
baidu_huihui14 分钟前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳16 分钟前
Python从入门到精通day63
开发语言·python
lbb 小魔仙16 分钟前
Python_RAG知识库问答系统实战指南
开发语言·python
java1234_小锋17 分钟前
Java高频面试题:Springboot的自动配置原理?
java·spring boot·面试
末央&1 小时前
【天机论坛】项目环境搭建和数据库设计
java·数据库
枫叶落雨2221 小时前
ShardingSphere 介绍
java
花花鱼1 小时前
Spring Security 与 Spring MVC
java·spring·mvc