近来写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,感谢前辈的指点。
网友评论