enable –打开蓝牙
public boolean enable() {
android.util.SeempLog.record(56);
if (isEnabled()) {
if (DBG) Log.d(TAG, "enable(): BT already enabled!");
return true;
}
try {
return mManagerService.enable(ActivityThread.currentPackageName());
} catch (RemoteException e) {Log.e(TAG, "", e);}
return false;
}
1、App通过BluetoothAdapter调用enable接口
2、在BluetoothAdapter 的getDefaultAdapter 中获取BluetoothManagerService服务客户端的代理对象managerService
IBinder b = ServiceManager.getService(BLUETOOTH_MANAGER_SERVICE);
if (b != null) {
IBluetoothManager managerService = IBluetoothManager.Stub.asInterface(b);//获得bind proxy
sAdapter = new BluetoothAdapter(managerService);
} else {
Log.e(TAG, "Bluetooth binder is null");
}
3、通过managerService的regiserAdapter获取AdapterService服务的客户端代理对象mService
private IBluetooth mService;
BluetoothAdapter(IBluetoothManager managerService) {
if (managerService == null) {
throw new IllegalArgumentException("bluetooth manager service is null");
}
try {
mServiceLock.writeLock().lock();
mService = managerService.registerAdapter(mManagerCallback);//IBluetooth proxy
} catch (RemoteException e) {
Log.e(TAG, "", e);
} finally {
mServiceLock.writeLock().unlock();
}
mManagerService = managerService;
mLeScanClients = new HashMap<LeScanCallback, ScanCallback>();
mToken = new Binder();
}
4、服务连接的时候获取AdapterService的客户端代理对象mBluetooth
private class BluetoothServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName componentName, IBinder service) {
String name = componentName.getClassName();
if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + name);
Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
msg.arg1 = SERVICE_IBLUETOOTH;
} else if (name.equals("com.android.bluetooth.gatt.GattService")) {
msg.arg1 = SERVICE_IBLUETOOTHGATT;
} else {
Slog.e(TAG, "Unknown service connected: " + name);
return;
}
msg.obj = service;
mHandler.sendMessage(msg);
}
case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
{
if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
IBinder service = (IBinder) msg.obj;
mBluetoothBinder = service;
mBluetooth = IBluetooth.Stub.asInterface(Binder.allowBlocking(service));
AdapterService –enable
打开蓝牙之前,先启动并初始化GattService。等GattService启动成功后发送BLE_STARTED消息,
然后在调用enableNative去打开蓝牙。