Android 蓝牙可见性开启与关闭

定制的Android设备只有在蓝牙页面才能被扫描搜索到,要求软件开启启动后作为服务端被蓝牙连接,且一直处于被发现状态。

最初尝试了下面的方法,但是有时间限制而且需要手动确认:

//启动修改蓝牙可见性的Intent
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//设置蓝牙可见性的时间,方法本身规定最多可见300秒
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(intent);

后来,发现调用反射方法开启蓝牙可见性,可以到达预期效果,如下:

public static void setDiscoverableTimeout() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    try {
        Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
        setDiscoverableTimeout.setAccessible(true);
        Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class);
        setScanMode.setAccessible(true);
        setDiscoverableTimeout.invoke(adapter, 0);
        setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, 0);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("Bluetooth", "setDiscoverableTimeout failure:" + e.getMessage());
    }
}

关闭可见性方法:

public static void closeDiscoverableTimeout() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    try {
        Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
        setDiscoverableTimeout.setAccessible(true);
        Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class);
        setScanMode.setAccessible(true);
        setDiscoverableTimeout.invoke(adapter, 1);
        setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE, 1);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

欢迎访问Github项目获取更多内容:

https://github.com/MickJson

欢迎点赞/评论,你们的赞同和鼓励是我写作的最大动力!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容