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();
    }
相关推荐
萧鼎27 分钟前
Python并发编程库:Asyncio的异步编程实战
开发语言·数据库·python·异步
学地理的小胖砸27 分钟前
【一些关于Python的信息和帮助】
开发语言·python
疯一样的码农28 分钟前
Python 继承、多态、封装、抽象
开发语言·python
^velpro^29 分钟前
数据库连接池的创建
java·开发语言·数据库
你的小1031 分钟前
JavaWeb项目-----博客系统
android
秋の花37 分钟前
【JAVA基础】Java集合基础
java·开发语言·windows
小松学前端40 分钟前
第六章 7.0 LinkList
java·开发语言·网络
可峰科技1 小时前
斗破QT编程入门系列之二:认识Qt:编写一个HelloWorld程序(四星斗师)
开发语言·qt
全栈开发圈1 小时前
新书速览|Java网络爬虫精解与实践
java·开发语言·爬虫
面试鸭1 小时前
离谱!买个人信息买到网安公司头上???
java·开发语言·职场和发展