蓝牙设置页面源码位置
com.android.settings.bluetooth.BluetoothSettings
1. 该界面点击开启蓝牙开关后的调用startScanning()方法
public void startScanning(boolean force) {
// Only start if we're not already scanning
if (!mAdapter.isDiscovering()) {
if (!force) {
// Don't scan more than frequently than SCAN_EXPIRATION_MS,
// unless forced
if (mLastScan + SCAN_EXPIRATION_MS > System.currentTimeMillis()) {
return;
}
// If we are playing music, don't scan unless forced.
A2dpProfile a2dp = mProfileManager.getA2dpProfile();
if (a2dp != null && a2dp.isA2dpPlaying()) {
return;
}
}
if (mAdapter.startDiscovery()) {
mLastScan = System.currentTimeMillis();
}
}
}
最终调用了mAdapter.startDiscovery())方法开启扫描,这里的mAdapter就是BluetoothAdapter,即系统设置最后就是通过BluetoothAdapter.startDiscovery()来进行扫描的
2. BluetoothAdapter.startDiscovery()
public boolean startDiscovery() {
if (getState() != STATE_ON) return false;
try {
synchronized(mManagerCallback) {
if (mService != null) return mService.startDiscovery();
}
} catch (RemoteException e) {Log.e(TAG, "", e);}
return false;
}
可以看到最后通过binder调用远程蓝牙系统服务
3. 事实上蓝牙系统服务最终会同过jni透过hal层调用模块底层驱动完成扫描,暂时没时间此处分析暂留
4. 底层的扫描结果同样是通过jni回调返回给framework的远程蓝牙服务的,最后通过广播i形式发送出去
com.android.bluetooth.btservice.JniCallbacks
void deviceFoundCallback(byte[] address) {
// The device properties are already registered - we can send the intent
// now
BluetoothDevice device = getDevice(address);
debugLog("deviceFoundCallback: Remote Address is:" + device);
DeviceProperties deviceProp = getDeviceProperties(device);
if (deviceProp == null) {
errorLog("Device Properties is null for Device:" + device);
return;
}
Intent intent = new Intent(BluetoothDevice.ACTION_FOUND);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
intent.putExtra(BluetoothDevice.EXTRA_CLASS,
new BluetoothClass(deviceProp.mBluetoothClass));
intent.putExtra(BluetoothDevice.EXTRA_RSSI, deviceProp.mRssi);
intent.putExtra(BluetoothDevice.EXTRA_NAME, deviceProp.mName);
mAdapterService.sendBroadcastMultiplePermissions(intent,
new String[] {AdapterService.BLUETOOTH_PERM,
android.Manifest.permission.ACCESS_COARSE_LOCATION});
}
注册android.bluetooth.device.action.FOUND可以接收到该广播
注意看这里要求了android.Manifest.permission.ACCESS_COARSE_LOCATION权限