Android 蓝牙可见性开启与关闭

本文介绍了如何使Android设备在软件启动后作为蓝牙服务端保持被发现状态,从而避免手动开启蓝牙可见性和时间限制。通过反射方法可以实现这一功能,详细步骤和代码可在作者的Github项目中获取。

定制的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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值