定制的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項目獲取更多內容:
歡迎點贊/評論,你們的贊同和鼓勵是我寫作的最大動力!
關注公眾號:幾圈年輪,查看更多有趣的技術資源。