android 蓝牙打开关闭和连接断开状态的判断

1.bluetooth常用api

1.BluetoothAdapter 蓝牙适配器,直到我们建立bluetoothSocket连接之前,都要不断操作它BluetoothAdapter里的方法很多,常用的有以下几个:
cancelDiscovery() 根据字面意思,是取消发现,也就是说当我们正在搜索设备的时候调用这个方法将不再继续搜索
disable()关闭蓝牙
enable()打开蓝牙,这个方法打开蓝牙不会弹出提示,更多的时候我们需要问下用户是否打开,一下这两行代码同样是打开蓝牙,不过会提示用户:
Intemtenabler=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enabler,reCode);//同startActivity(enabler);
getAddress()获取本地蓝牙地址
getDefaultAdapter()获取默认BluetoothAdapter,实际上,也只有这一种方法获取BluetoothAdapter
getName()获取本地蓝牙名称
getRemoteDevice(String address)根据蓝牙地址获取远程蓝牙设备
getState()获取本地蓝牙适配器当前状态(感觉可能调试的时候更需要)
isDiscovering()判断当前是否正在查找设备,是返回true
isEnabled()判断蓝牙是否打开,已打开返回true,否则,返回false
listenUsingRfcommWithServiceRecord(String name,UUID uuid)根据名称,UUID创建并返回BluetoothServerSocket,这是创建BluetoothSocket服务器端的第一步
startDiscovery()开始搜索,这是搜索的第一步

首先,要操作蓝牙,先要在AndroidManifest.xml里加入权限

<uses-permissionandroid:name=“android.permission.BLUETOOTH_ADMIN” />

<uses-permissionandroid:name=“android.permission.BLUETOOTH” />

1、获取本地蓝牙适配器

      BluetoothAdapter
mAdapter= BluetoothAdapter.getDefaultAdapter();

      2、打开蓝牙

      if(!mAdapter.isEnabled()){

//弹出对话框提示用户是后打开

Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enabler, REQUEST_ENABLE);

      //不做提示,强行打开

      // mAdapter.enable();

}

2 定义BroadcastReceiver

BroadcastReceiver mReceiver = new BroadcastReceiver() {



public void onReceive(Context context, Intent intent) {


String action = intent.getAction();

                   //找到设备


if (BluetoothDevice.ACTION_FOUND.equals(action)) {



BluetoothDevice device = intent

.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);



if (device.getBondState() != BluetoothDevice.BOND_BONDED) {



Log.v(TAG, "find device:" + device.getName()

+ device.getAddress());



}


}


         //搜索完成


        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED

.equals(action)) {


setTitle("搜索完成");


if (mNewDevicesAdapter.getCount() == 0) {


Log.v(TAG,"find over");


}


}


//执行更新列表的代码


}


};

BroadcastReceiver,具体代码如下

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);


registerReceiver(mReceiver, filter);


filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);


registerReceiver(mReceiver, filter);

1.开机检测蓝牙连接状态

//蓝牙已打开
		if(mAdapter.isEnabled()){
			
			int a2dp = mAdapter.getProfileConnectionState(BluetoothProfile.A2DP); // 可操控蓝牙设备,如带播放暂停功能的蓝牙耳机
			int headset = mAdapter.getProfileConnectionState(BluetoothProfile.HEADSET); // 蓝牙头戴式耳机,支持语音输入输出
			int health = mAdapter.getProfileConnectionState(BluetoothProfile.HEALTH); // 蓝牙穿戴式设备
			int GATT = mAdapter.getProfileConnectionState(BluetoothProfile.GATT);
			Log.e("lqq","a2dp="+a2dp+",headset="+headset+",health="+health);
			// 查看是否蓝牙是否连接到三种设备的一种,以此来判断是否处于连接状态还是打开并没有连接的状态
			int flag = -1;
			if (a2dp == BluetoothProfile.STATE_CONNECTED) {
				flag = a2dp;
			} else if (headset == BluetoothProfile.STATE_CONNECTED) {
				flag = headset;
			} else if (health == BluetoothProfile.STATE_CONNECTED) {
				flag = health;
			}
			if (flag != -1) {
				setBtState(BluetoothAdapter.STATE_CONNECTED); // disconnected
			} else if (flag == -1) {
				//蓝牙手机相互配对连接
				NetworkInfo netInfo = ((ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE)).getNetworkInfo(ConnectivityManager.TYPE_BLUETOOTH);
				if (netInfo == null) {
					setBtState(BluetoothAdapter.STATE_ON);  // disconnected
				} else {
					setBtState(BluetoothAdapter.STATE_CONNECTED); // 系统内部,返回连接与否// connected
				}
			}
		} else {
			setBtState(BluetoothAdapter.STATE_OFF);// disconnected
		}

2.权限的申请

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

3.打开和关闭状态

private IntentFilter makeFilter() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    return filter;
}
 
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
 
    @Override
    public void onReceive(Context context, Intent intent) {
        LogUtil.e(TAG, "onReceive---------");
        switch (intent.getAction()) {
            case BluetoothAdapter.ACTION_STATE_CHANGED:
                int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                switch (blueState) {
                    case BluetoothAdapter.STATE_TURNING_ON:
                        LogUtil.e("onReceive---------STATE_TURNING_ON");
                        break;
                    case BluetoothAdapter.STATE_ON:
                        LogUtil.e("onReceive---------STATE_ON");
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        LogUtil.e("onReceive---------STATE_TURNING_OFF");
                        BleUtil.toReset(mContext);
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        LogUtil.e("onReceive---------STATE_OFF");
                        BleUtil.toReset(mContext);
                        break;
                }
                break;
        }
    }
};

4.连接和断开状态

private void registerBoradcastReceiver() {
		//注册监听
        IntentFilter stateChangeFilter = new IntentFilter(
                BluetoothAdapter.ACTION_STATE_CHANGED);
        IntentFilter connectedFilter = new IntentFilter(
                BluetoothDevice.ACTION_ACL_CONNECTED);
        IntentFilter disConnectedFilter = new IntentFilter(
                BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(stateChangeReceiver, stateChangeFilter);
        registerReceiver(stateChangeReceiver, connectedFilter);
        registerReceiver(stateChangeReceiver, disConnectedFilter);
    }
 
    private BroadcastReceiver stateChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
                //连接上了
            } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
                //蓝牙连接被切断
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String name = device.getName();
                ViewUtils.showToast(name + "的连接被断开", getApplicationContext());
                isConnected = false;
                return;
            }
        }
    };
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Android 中,断开连接和取消配对的广播分别是 ACTION_ACL_DISCONNECTED 和 ACTION_BOND_STATE_CHANGED。 ACTION_ACL_DISCONNECTED 广播在 BluetoothAdapter 中定义,当蓝牙连接断开时发送。您可以使用以下代码注册和接收此广播: ``` private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothAdapter.ACTION_ACL_DISCONNECTED.equals(action)) { // 处理断开连接的逻辑 } } }; IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_ACL_DISCONNECTED); registerReceiver(mReceiver, filter); ``` ACTION_BOND_STATE_CHANGED 广播在 BluetoothDevice 中定义,当蓝牙设备配对状态更改时发送。您可以使用以下代码注册和接收此广播: ``` private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR); int previousBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR); if (bondState == BluetoothDevice.BOND_NONE && previousBondState == BluetoothDevice.BOND_BONDED) { // 处理取消配对的逻辑 } } } }; IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED); registerReceiver(mReceiver, filter); ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安卓兼职framework应用工程师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值