Android开发——蓝牙状态变化的监听

今天遇到个问题,需要对蓝牙状态进行监听。这个功能之前做过,一直没有总结记录过,今天又遇到了,就记录一下蓝牙状态的监听过程。

首先写一个广播接收器,主要实现蓝牙状态变化的广播接收。

import android.bluetooth.BluetoothAdapter;

import android.bluetooth.BluetoothDevice;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.widget.Toast;

public class BluetoothStateBroadcastReceive extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

String action = intent.getAction();

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

switch (action){

case BluetoothDevice.ACTION_ACL_CONNECTED:

Toast.makeText(context , "蓝牙设备:" + device.getName() + "已链接", Toast.LENGTH_SHORT).show();

break;

case BluetoothDevice.ACTION_ACL_DISCONNECTED:

Toast.makeText(context , "蓝牙设备:" + device.getName() + "已断开", Toast.LENGTH_SHORT).show();

break;

case BluetoothAdapter.ACTION_STATE_CHANGED:

int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);

switch (blueState){

case BluetoothAdapter.STATE_OFF:

Toast.makeText(context , "蓝牙已关闭", Toast.LENGTH_SHORT).show();

break;

case BluetoothAdapter.STATE_ON:

Toast.makeText(context , "蓝牙已开启" , Toast.LENGTH_SHORT).show();

break;

}

break;

}

}

}

然后注册上面这个广播接收器,这里就要根据具体需要可选择静态注册或动态注册了。

静态注册方法

动态注册方法

首先定义一个接收器对象

private BluetoothStateBroadcastReceive mReceive;

然后写注册方法

private void registerBluetoothReceiver(){

if(mReceive == null){

mReceive = new BluetoothStateBroadcastReceive();

}

IntentFilter intentFilter = new IntentFilter();

intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);

intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);

intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF");

intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_ON");

registerReceiver(mReceive, intentFilter);

}

再不需要的时候记得要注销,注销方法

private void unregisterBluetoothReceiver(){

if(mReceive != null){

unregisterReceiver(mReceive);

mReceive = null;

}

}

转载于:android 蓝牙状态变化,Android开发——蓝牙状态的监听_邢不行的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/weixin_42602900/article/details/126134411