您无法使用第三方(非内核/非系统)应用程序设置 4.2 及更高版本的 Android 设备的扫描模式。您只能启用发现 ( SCAN_MODE_CONNECTABLE_DISCOVERABLE
),并可选择使用 设置特定持续时间EXTRA_DISCOVERABLE_DURATION
。您可以通过将持续时间参数设置为 1来有效地取消发现。
作为证据,请浏览Android Source,重点关注BluetoothAdapter.java:
/**
* Set the Bluetooth scan mode of the local Bluetooth adapter.
* <p>The Bluetooth scan mode determines if the local adapter is
* connectable and/or discoverable from remote Bluetooth devices.
* <p>For privacy reasons, discoverable mode is automatically turned off
* after <code>duration</code> seconds. For example, 120 seconds should be
* enough for a remote device to initiate and complete its discovery
* process.
* <p>Valid scan mode values are:
* {@link #SCAN_MODE_NONE},
* {@link #SCAN_MODE_CONNECTABLE},
* {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}.
* <p>If Bluetooth state is not {@link #STATE_ON}, this API
* will return false. After turning on Bluetooth,
* wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
* to get the updated value.
* <p>Requires {@link android.Manifest.permission#WRITE_SECURE_SETTINGS}
* <p>Applications cannot set the scan mode. They should use
* <code>startActivityForResult(
* BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE})
* </code>instead.
*
* @param mode valid scan mode
* @param duration time in seconds to apply scan mode, only used for
* {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}
* @return true if the scan mode was set, false otherwise
* @hide
*/
public boolean setScanMode(int mode, int duration) {
if (getState() != STATE_ON) return false;
try {
synchronized(mManagerCallback) {
if (mService != null) return mService.setScanMode(mode, duration);
}
} catch (RemoteException e) {Log.e(TAG, "", e);}
return false;
}
如源代码中所述,“应用程序无法设置扫描模式”。需要WRITE_SECURE_SETTINGS权限才能在 API 之外手动扫描模式,第三方应用程序无法做到这一点。