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

相关推荐
XiYang-DING15 小时前
【MyBatis】${}与 #{}的区别
java·tomcat·mybatis
-凌凌漆-15 小时前
【Qt】std::shared_ptr<>与std::make_shared<>
开发语言·qt
_阿伟_16 小时前
计算机知识科普
java·开发语言
ulias21216 小时前
深挖进程间通信的奥秘
java·linux·服务器·开发语言·c++·算法
8Qi816 小时前
LeetCode 62 & 63:不同路径 I & II(含障碍物)
java·算法·leetcode·职场和发展·动态规划
于先生吖16 小时前
UniApp搭配Java后端实现到店预约上门指派,订单状态流转与结算开发教程
java·开发语言·uni-app
西安邮电大学16 小时前
binlog/redolog/undolog三者对比
java·后端·其他·面试
luj_176816 小时前
局部两极分析破解数学建模难题
服务器·c语言·开发语言·经验分享·算法
布朗克16816 小时前
17 常用工具类
java·开发语言·工具类