欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

监听蓝牙连接的状态

程序员文章站 2022-06-14 23:04:14
...

之前写的是监听蓝牙是否打开。这篇文章简单的介绍蓝牙的连接状态监听。忘记是哪位博主写的了。本人简单的整理下。代码其实就一个工具类而已:

package com.tools;

import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.service.PlayService;
import com.shouchiji.ConnectDev;
import com.ui.activity.MainActivity;
import com.shouchiji.R;

import static com.tools.Utils.page;
import static com.ui.activity.MainActivity.ifExit;

/**
 * 监听蓝牙的连接状态
 */
public class BlueToothReceiver extends BroadcastReceiver {

    private String btMessage = "";
    //监听蓝牙状态

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        //连接
        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            btMessage = device.getName();//蓝牙的名字
            //已经连接,开始你的操作,我是用了播放音乐的方式提醒客户
        } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            Log.e("断开", "onReceive: " + device.getName());//蓝牙的名字
            btMessage = device.getName() + "蓝牙连接已断开!!";
            //已经断开,开始你的操作,我是用了播放音乐的方式提醒客户,然后在activity里写了一个方法,继续连接。
           
        }
    }
}

清单文件:

<!--蓝牙监听-->
<receiver android:name="com.tools.BlueToothReceiver">
    <intent-filter>
        <action android:name="android.bluetooth.device.action.PAIRING_REQUEST" />
        <action android:name="android.bluetooth.device.action.ACTION_BOND_STATE_CHANGED" />
        <action android:name="android.bluetooth.device.action.ACL_CONNECTED"></action>
        <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED"></action>
        <action android:name="android.bluetooth.device.action.FOUND"></action>
        <action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED"></action>
    </intent-filter>
</receiver>