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

相关推荐
Boilermaker199218 分钟前
【Java EE】Mybatis-Plus
java·开发语言·java-ee
aramae24 分钟前
C++ -- STL -- vector
开发语言·c++·笔记·后端·visual studio
Tony小周24 分钟前
实现一个点击输入框可以弹出的数字软键盘控件 qt 5.12
开发语言·数据库·qt
xdscode39 分钟前
SpringBoot ThreadLocal 全局动态变量设置
java·spring boot·threadlocal
lifallen43 分钟前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法
lixzest44 分钟前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
丶小鱼丶1 小时前
链表算法之【合并两个有序链表】
java·算法·链表
沉默媛1 小时前
如何安装python以及jupyter notebook
开发语言·python·jupyter
张先shen1 小时前
Elasticsearch RESTful API入门:全文搜索实战(Java版)
java·大数据·elasticsearch·搜索引擎·全文检索·restful
_Chipen2 小时前
C++基础问题
开发语言·c++