android 经典蓝牙 设置永久可见性 可被查找到

近来写android设备的时候,有一个需要设备的经典蓝牙模块持续被搜索到的需求,再次记录下。

下面方法是可以实现的,但是时长只有120s,再安卓9.0以下会弹出一个弹出框。

Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, 0);
Toast.makeText(PortLoginAct.this, "蓝牙可检测性已打开", Toast.LENGTH_SHORT).show();

为了设置永久可见性,并且取消弹窗,可调用下面方法

/**
     * 开启蓝牙永久可见性
     */
    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);
            L.e("open Bluetooth search");
        } catch (Exception e) {
            e.printStackTrace();
            L.e("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);
            L.e("close Bluetooth search");
        } catch (Exception e) {
            e.printStackTrace();
            L.e("closeDiscoverableTimeout failure:" + e.getMessage());
        }
    }

转载https://www.jianshu.com/p/962ac40d7c9c,感谢前辈的指点。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容