1. Overview
藍牙初始化框圖如上:
- 藍牙處于關(guān)閉狀態(tài)時袋狞,進程 com.android.bluetooth 不存在佛致。
- 以設(shè)置打開藍牙為例晌柬,藍牙初始化(即 enable)的流程是 com.android.settings(設(shè)置進程) ----> system_server(系統(tǒng)服務(wù)進程)----> com.android.bluetooth(藍牙進程)
- 藍牙進程啟動之后识埋,設(shè)置應(yīng)用將直接與藍牙進程通信咪笑,無需再經(jīng)過系統(tǒng)服務(wù)進程浸剩。
2. Settings Process - 觸發(fā)開啟藍牙
frameworks/base/core/java/android/bluetooth/BluetoothAdapter.java
public boolean enable() {
......
try {
return mManagerService.enable(ActivityThread.currentPackageName());
} catch (RemoteException e) {
Log.e(TAG, "", e);
}
return false;
}
3. System_server Process
3.1 啟動藍牙進程
frameworks/base/services/core/java/com/android/server/BluetoothManagerService.java
public boolean enable(String packageName) throws RemoteException {
......
synchronized (mReceiver) {
......
sendEnableMsg(false,
BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST, packageName);
}
return true;
}
此處傳遞的 quietMode = false钾军;
private void sendEnableMsg(boolean quietMode, int reason, String packageName) {
mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE, quietMode ? 1 : 0, 0));
......
}
private class BluetoothHandler extends Handler {
......
@Override
public void handleMessage(Message msg) {
case MESSAGE_ENABLE:
......
mQuietEnable = (msg.arg1 == 1); // mQuietEnable = false;
if (mBluetooth == null) {
handleEnable(mQuietEnable);
}
......
break;
首次開啟時,由于 com.android.bluetooth 還未啟動绢要,因此 mBluetooth == null吏恭,故會執(zhí)行綁定服務(wù)的操作。
private void handleEnable(boolean quietMode) {
mQuietEnable = quietMode; // false
try {
if ((mBluetooth == null) && (!mBinding)) {
......
Intent i = new Intent(IBluetooth.class.getName());
if (!doBind(i, mConnection,
Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
UserHandle.CURRENT)) {
} else {
mBinding = true;
}
} else if (mBluetooth != null) {
......
}
}
}
boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
intent.setComponent(comp);
if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
return false;
}
return true;
}
綁定的是 IBluetooth 這個服務(wù)重罪,由以下配置信息可知樱哼,綁定的是 AdapterService.java哀九,該綁定過程會啟動 com.android.bluetooth 進程。
packages/apps/Bluetooth/AndroidManifest.xml
<service android:process="@string/process"
android:name=".btservice.AdapterService"
android:exported="true">
<intent-filter>
<action android:name="android.bluetooth.IBluetooth"/>
</intent-filter>
</service>
藍牙進程的啟動過程由 藍牙進程初始化 來分析唇礁,此文繼續(xù)分析服務(wù)被綁定成功后的回調(diào)勾栗。
3.2 綁定 AdapterService 成功后的回調(diào)
frameworks/base/services/core/java/com/android/server/BluetoothManagerService.java
private class BluetoothServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName componentName, IBinder service) {
String name = componentName.getClassName();
Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
msg.arg1 = SERVICE_IBLUETOOTH;
......
}
msg.obj = service;
mHandler.sendMessage(msg);
}
......
}
private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
以上源碼主要是創(chuàng)建了 MESSAGE_BLUETOOTH_SERVICE_CONNECTED 消息,下面開始處理該消息盏筐。
private class BluetoothHandler extends Handler {
......
@Override
public void handleMessage(Message msg) {
case MESSAGE_BLUETOOTH_SERVICE_CONNECTED: {
IBinder service = (IBinder) msg.obj;
try {
mBluetoothLock.writeLock().lock();
if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
......
return;
} // else must be SERVICE_IBLUETOOTH
......
mBinding = false;
mBluetoothBinder = service;
// 0. 獲取藍牙進程藍牙適配器服務(wù)的代理對象
mBluetooth = IBluetooth.Stub.asInterface(Binder.allowBlocking(service));
......
// 1. 向藍牙進程注冊回調(diào)函數(shù)围俘,以達到雙向通信的目的
try {
mBluetooth.registerCallback(mBluetoothCallback);
} catch (RemoteException re) {
Slog.e(TAG, "Unable to register BluetoothCallback", re);
}
// 2. Inform BluetoothAdapter instances that service is up
sendBluetoothServiceUpCallback();
// 3. Do enable request
try {
if (!mBluetooth.enable(mQuietEnable)) {
Slog.e(TAG, "IBluetooth.enable() returned false");
}
} catch (RemoteException e) {
Slog.e(TAG, "Unable to call enable()", e);
}
處理 MESSAGE_BLUETOOTH_SERVICE_CONNECTED 消息,從源碼可知:
首先琢融,獲取并保存藍牙進程入口的代理對象:mBluetooth界牡;
其次,
- 向藍牙進程注冊回調(diào)漾抬,用于藍牙進程向系統(tǒng)服務(wù)進程發(fā)送消息宿亡;
- 執(zhí)行應(yīng)用層注冊到系統(tǒng)服務(wù)進程的回調(diào),向已注冊的應(yīng)用進程提供 藍牙進程入口的代理對象纳令;
- 向藍牙進程發(fā)起執(zhí)行 enable 操作的請求挽荠。
3.2.1 registerCallback
3.2.1.1 Register Flow
packages/apps/Bluetooth/src/com/android/bluetooth/btservice/AdapterService.java
AdapterService 存儲該回調(diào)對象,在合適的時候觸發(fā)回調(diào)平绩。
public class AdapterService extends Service {
private RemoteCallbackList<IBluetoothCallback> mCallbacks =
new RemoteCallbackList<IBluetoothCallback>();
public static class AdapterServiceBinder extends IBluetooth.Stub {
public void registerCallback(IBluetoothCallback callback) {
AdapterService service = getService();
......
service.mCallbacks.register(callback);
}
}
3.2.1.2 Callback Implementation
frameworks/base/services/core/java/com/android/server/BluetoothManagerService.java
private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
@Override
public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
Message msg =
mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE, prevState, newState);
mHandler.sendMessage(msg);
}
};
從以上源碼可知圈匆,藍牙進程調(diào)用該回調(diào)以通知系統(tǒng)服務(wù)進程藍牙的狀態(tài)變化信息。
private class BluetoothHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_BLUETOOTH_STATE_CHANGE: {
int prevState = msg.arg1;
int newState = msg.arg2;
mState = newState;
bluetoothStateChangeHandler(prevState, newState);
......
break;
}
bluetoothStateChangeHandler() 負責(zé)更新狀態(tài)捏雌,并發(fā)送狀態(tài)變化的廣播跃赚。
3.2.1.3 Callback Invoke Example
回調(diào)方法執(zhí)行的源碼如下
packages/apps/Bluetooth/src/com/android/bluetooth/btservice/AdapterService.java
void updateAdapterState(int prevState, int newState) {
......
if (mCallbacks != null) {
int n = mCallbacks.beginBroadcast();
for (int i = 0; i < n; i++) {
try {
mCallbacks.getBroadcastItem(i).onBluetoothStateChange(prevState, newState);
} catch (RemoteException e) {
......
}
}
mCallbacks.finishBroadcast();
}
frameworks/base/core/java/android/os/RemoteCallbackList.java
public class RemoteCallbackList<E extends IInterface> {
public int beginBroadcast() {
synchronized (mCallbacks) {
final int N = mBroadcastCount = mCallbacks.size();
if (N <= 0) {
return 0;
}
Object[] active = mActiveBroadcast;
if (active == null || active.length < N) {
mActiveBroadcast = active = new Object[N];
}
for (int i=0; i<N; i++) {
active[i] = mCallbacks.valueAt(i);
}
return N;
}
}
public void finishBroadcast() {
synchronized (mCallbacks) {
Object[] active = mActiveBroadcast;
if (active != null) {
final int N = mBroadcastCount;
for (int i=0; i<N; i++) {
active[i] = null;
}
}
mBroadcastCount = -1;
}
}
}
3.2.2 sendBluetoothServiceUpCallback
frameworks/base/services/core/java/com/android/server/BluetoothManagerService.java
private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks =
new RemoteCallbackList<IBluetoothManagerCallback>();;
private void sendBluetoothServiceUpCallback() {
synchronized (mCallbacks) {
try {
int n = mCallbacks.beginBroadcast();
for (int i = 0; i < n; i++) {
try {
mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
} catch (RemoteException e) {
Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
}
}
} finally {
mCallbacks.finishBroadcast();
}
}
}
BluetoothManagerService 回調(diào)應(yīng)用層注冊的回調(diào)對象的方法 onBluetoothServiceUp(),將藍牙進程入口的代理對象發(fā)送到該應(yīng)用性湿。
frameworks/base/core/java/android/bluetooth/BluetoothDevice.java
public final class BluetoothDevice implements Parcelable {
static IBluetoothManagerCallback sStateChangeCallback = new IBluetoothManagerCallback.Stub() {
public void onBluetoothServiceUp(IBluetooth bluetoothService)
throws RemoteException {
synchronized (BluetoothDevice.class) {
if (sService == null) {
sService = bluetoothService;
}
}
}
......
}
}
3.2.3 Bluetooth Process enable
藍牙進程繼續(xù)執(zhí)行 enable 操作的內(nèi)容較多纬傲,鏈接如下。
Bluetooth initialization - enable in Bluetooth process