近來寫android設(shè)備的時(shí)候,有一個(gè)需要設(shè)備的經(jīng)典藍(lán)牙模塊持續(xù)被搜索到的需求,再次記錄下。
下面方法是可以實(shí)現(xiàn)的,但是時(shí)長(zhǎng)只有120s,再安卓9.0以下會(huì)彈出一個(gè)彈出框。
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, 0);
Toast.makeText(PortLoginAct.this, "藍(lán)牙可檢測(cè)性已打開", Toast.LENGTH_SHORT).show();
為了設(shè)置永久可見性,并且取消彈窗,可調(diào)用下面方法
/**
* 開啟藍(lán)牙永久可見性
*/
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());
}
}
/**
* 關(guān)閉藍(lán)牙永久可見性
*/
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());
}
}
轉(zhuǎn)載http://www.itdecent.cn/p/962ac40d7c9c,感謝前輩的指點(diǎn)。