android中将蓝牙设置为始终可发现模式

BlueAlwaysDiscoverableReceiver.java

java 复制代码
package com.ks.xybase.receiver;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;


import com.ks.xybase.utils.L;

import java.lang.reflect.Method;
import java.util.Objects;

//蓝牙设置为始终可发现模式
public class BlueAlwaysDiscoverableReceiver extends BroadcastReceiver {
    private static final String TAG = "BlueAlwaysDiscoverableR";
    private Context mContext;
    private BluetoothAdapter mBluetoothAdapter;
    private IntentFilter mIntentFilter;

    public BlueAlwaysDiscoverableReceiver(Context context) {
        mContext = context;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
    }

    public void start() {
        mContext.registerReceiver(this, mIntentFilter);
        setBlueCanVisible();
    }

    public void stop() {
        mContext.unregisterReceiver(this);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (!Objects.equals(action, BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
            return;
        }
        setBlueCanVisible();
    }

    private void setBlueCanVisible() {
        try {
            Method setScanModeMethod = BluetoothAdapter.class.getMethod("setScanMode", int.class);
            setScanModeMethod.setAccessible(true);
            setScanModeMethod.invoke(mBluetoothAdapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
        } catch (Exception e) {
            L.d(TAG, "error when setBlueCanVisible,e==" + e.getMessage());
        }
    }
}

然后在activity中

java 复制代码
private BlueAlwaysDiscoverableReceiver mBlueAlwaysDiscoverableReceiver;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //设置蓝牙为始终被发现模式
        mBlueAlwaysDiscoverableReceiver = new BlueAlwaysDiscoverableReceiver(this);
        mBlueAlwaysDiscoverableReceiver.start();
    }

 @Override
    protected void onDestroy() {
        mBlueAlwaysDiscoverableReceiver.stop();
        super.onDestroy();
    }
相关推荐
寻星探路7 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
工程师老罗9 小时前
如何在Android工程中配置NDK版本
android
lly2024069 小时前
Bootstrap 警告框
开发语言
2601_949146539 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧9 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX10 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb010310 小时前
C++课后习题训练记录Day98
开发语言·c++
猫头虎11 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
YUJIANYUE11 小时前
PHP纹路验证码
开发语言·php
仟濹11 小时前
【Java基础】多态 | 打卡day2
java·开发语言