一、BluetoothAdapter:
BluetoothAdapter代表设备自身的蓝牙适配器。整个系统只有一个蓝牙适配器,通过framework层提供的公共接口getDefaultAdapter方法来获取这个对象。应用如果要操作蓝牙首先就要获得BluetoothAdapter。
1. 应用层:
方法一: 通过BluetoothManagerService返回的IBluetoothManager.aidl接口的实现类。
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
查看BluetoothManagerService的定义:
class BluetoothManagerService extends IBluetoothManager.Stub
方法二:
BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();
2. framework层:
BluetoothAdapter 的getDefaultAdapter方法,该方法通过BluetoothManagerService.java提供的binder( IBluetoothManager)对象,创建了BluetoothAdapter这个实例
private static BluetoothAdapter sAdapter;
public static synchronized BluetoothAdapter getDefaultAdapter() {
if (sAdapter == null) {
IBinder b = ServiceManager.getService(BLUETOOTH_MANAGER_SERVICE);
if (b != null) {
IBluetoothManager managerService = IBluetoothManager.Stub.asInterface(b);
sAdapter = new BluetoothAdapter(managerService);
} else {
Log.e(TAG, "Bluetooth binder is null");
}
}
return sAdapter;
}
二、AdapterService:
Bluetooth 应用的核心服务,该服务通过JNI调用bluetooth.defualt.so的接口。
1. 启动
在蓝牙enable的时候,BluetoothManagerService在其中enable方法会启动一个service,这个service就是AdapterService。
class BluetoothManagerService extends IBluetoothManager.Stub
|enable()
|sendEnableMsg(false);
|mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,0, 0));
在他的内部类BluetoothHandler继承了Handler类,处理传递的消息:
|handleMessage(Message msg)
|case MESSAGE_ENABLE
|handleEnable(msg.arg1 == 1); // msg.arg1 = 0
|if ((mBluetooth == null) && (!mBinding))
|Intent i = new Intent(IBluetooth.class.getName());
|doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
启动AdapterService服务
|doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
|mContext.bindServiceAsUser(intent, conn, flags, user);
// 启动AdapterService服务后会回调mConnection的onServiceConnected()方法
| onServiceConnected(ComponentName className, IBinder service)
| Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
| if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService"))
|msg.arg1 = SERVICE_IBLUETOOTH;
|else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService"))
|msg.arg1 = SERVICE_IBLUETOOTHGATT;
|msg.obj = service;
|mHandler.sendMessage(msg);
发出的MESSAGE_BLUETOOTH_SERVICE_CONNECTED消息在handleMessage处理,继续打开蓝牙,此处不做描述。
2. 常用native函数
private native static void classInitNative();
private native boolean initNative();
/*package*/ native boolean enableNative();
/*package*/ native boolean disableNative();
/*package*/ native boolean createBondNative(byte[] address, int transport);
/*package*/ native boolean removeBondNative(byte[] address);
/*package*/ native boolean cancelBondNative(byte[] address);
private native boolean startDiscoveryNative();
private native boolean cancelDiscoveryNative();
以上native函数实现在com_android_bluetooth_btservice_AdapterService.cpp中。