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

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

关注公众号:几圈年轮,查看更多有趣的技术资源。

posted @ 2020-08-12 14:30  几圈年轮  阅读(1747)  评论(0编辑  收藏  举报