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博客

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值