http://blog.csdn.net/uyiwfn/article/details/8808131
\external\bluetooth\bluedroid\audio_a2dp_hw\audio_a2dp_hw.cpp
编译生成audio.a2dp.default.so,主要实现a2dp做为设备的功能
- struct audio_module HAL_MODULE_INFO_SYM = {
- .common = {
- .tag = HARDWARE_MODULE_TAG,
- .version_major = 1,
- .version_minor = 0,
- .id = AUDIO_HARDWARE_MODULE_ID,
- .name = "A2DP Audio HW HAL",
- .author = "The Android Open Source Project",
- .methods = &hal_module_methods,
- },
- };
\hardware\libhardware_legacy\audio\audio_policy_hal.cpp
编译生成libaudiohw_legacy.so,是audio_policy的HAL层,不同厂商可以有自己的audio_policy。
- struct legacy_ap_module HAL_MODULE_INFO_SYM = {
- module: {
- common: {
- tag: HARDWARE_MODULE_TAG,
- version_major: 1,
- version_minor: 0,
- id: AUDIO_POLICY_HARDWARE_MODULE_ID,
- name: "LEGACY Audio Policy HAL",
- author: "The Android Open Source Project",
- methods: &legacy_ap_module_methods,
- dso : NULL,
- reserved : {0},
- },
- },
- };
audio_policy.conf
该文件最后放在/system/etc/ 下,其定义了系统的音频设备,其中AUDIO_HARDWARE_MODULE_ID =“a2dp”,AudioPolicyService中的load_audio_interface根据AUDIO_HARDWARE_MODULE_ID来加载对应的audio库。
- audio_hw_modules {
- primary {
- outputs {
- primary {
- sampling_rates 44100
- channel_masks AUDIO_CHANNEL_OUT_STEREO
- formats AUDIO_FORMAT_PCM_16_BIT
- devices AUDIO_DEVICE_OUT_EARPIECE|AUDIO_DEVICE_OUT_SPEAKER|AUDIO_DEVICE_OUT_WIRED_HEADSET|AUDIO_DEVICE_OUT_WIRED_HEADPHONE|AUDIO_DEVICE_OUT_ALL_SCO|AUDIO_DEVICE_OUT_AUX_DIGITAL|AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET
- flags AUDIO_OUTPUT_FLAG_PRIMARY
- }
- }
- inputs {
- primary {
- sampling_rates 8000|11025|16000|22050|32000|44100|48000
- channel_masks AUDIO_CHANNEL_IN_MONO|AUDIO_CHANNEL_IN_STEREO
- formats AUDIO_FORMAT_PCM_16_BIT
- devices AUDIO_DEVICE_IN_BUILTIN_MIC|AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET|AUDIO_DEVICE_IN_WIRED_HEADSET
- }
- }
- }
- a2dp {
- outputs {
- a2dp {
- sampling_rates 44100
- channel_masks AUDIO_CHANNEL_OUT_STEREO
- formats AUDIO_FORMAT_PCM_16_BIT
- devices AUDIO_DEVICE_OUT_ALL_A2DP
- }
- }
- }
- }
下图是一张a2dp模块初始化的流程,其主要是加载了a2dp的audio库,并audio policy中注册了一个a2dp音频设备:
BluetoothManagerService绑定IBluetooth过程
- public void getNameAndAddress() {
- if (DBG) {
- Log.d(TAG,"getNameAndAddress(): mBluetooth = " + mBluetooth +
- " mBinding = " + mBinding);
- }
- Message msg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
- mHandler.sendMessage(msg);
- }
BluetoothHandler::handleMessage
- case MESSAGE_GET_NAME_AND_ADDRESS: {
- if (DBG) Log.d(TAG,"MESSAGE_GET_NAME_AND_ADDRESS");
- synchronized(mConnection) {
- //Start bind request
- if ((mBluetooth == null) && (!mBinding)) {
- if (DBG) Log.d(TAG, "Binding to service to get name and address");
- mConnection.setGetNameAddressOnly(true);
- //Start bind timeout and bind
- Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
- mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
- Intent i = new Intent(IBluetooth.class.getName());
- if (!mContext.bindService(i, mConnection,
- Context.BIND_AUTO_CREATE, UserHandle.USER_CURRENT)) {
- mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
- Log.e(TAG, "fail to bind to: " + IBluetooth.class.getName());
- } else {
- mBinding = true;
- }
- }
在这里调用了bindService来绑定服务,成功后调用mConnection的onServiceConnected
- private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
- private class BluetoothServiceConnection implements ServiceConnection {
- private boolean mGetNameAddressOnly;
- public void setGetNameAddressOnly(boolean getOnly) {
- mGetNameAddressOnly = getOnly;
- }
- public boolean isGetNameAddressOnly() {
- return mGetNameAddressOnly;
- }
- public void onServiceConnected(ComponentName className, IBinder service) {
- if (DBG) Log.d(TAG, "BluetoothServiceConnection: connected to AdapterService className:"+className+" service:",service);
- Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
- msg.obj = service;
- mHandler.sendMessage(msg);
- }
- public void onServiceDisconnected(ComponentName className) {
- // Called if we unexpected disconnected.
- if (DBG) Log.d(TAG, "BluetoothServiceConnection: disconnected from AdapterService");
- Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
- mHandler.sendMessage(msg);
- }
onServiceConnected调用完成后再次到
BluetoothHandler::handleMessage,处理打开BT的消息
以下是BluetoothAdapter的构造过程,向RemoteCallbackList中注册了一个IBluetoothManagerCallback,用来与BluetoothManagerService通信。
E:\BOX_4.2\frameworks\base\core\java\android\bluetooth\BluetoothAdapter.cpp
- BluetoothAdapter(IBluetoothManager managerService) {
- if (managerService == null) {
- throw new IllegalArgumentException("bluetooth manager service is null");
- }
- try {
- mService = managerService.registerAdapter(mManagerCallback);
- } catch (RemoteException e) {Log.e(TAG, "", e);}
- mManagerService = managerService;
- mServiceRecordHandler = null;
- if (DBG) Log.d(TAG, "BluetoothAdapter" + ": mService ="+mService+ ": mManagerService ="+mManagerService+
- ": mManagerCallback ="+mManagerCallback);
- }
- <p> final private IBluetoothManagerCallback mManagerCallback =
- new IBluetoothManagerCallback.Stub() {
- public void onBluetoothServiceUp(IBluetooth bluetoothService) {
- if (VDBG) Log.d(TAG, "onBluetoothServiceUp: " + bluetoothService);
- synchronized (mManagerCallback) {
- mService = bluetoothService;
- for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){
- try {
- if (cb != null) {
- cb.onBluetoothServiceUp(bluetoothService);
- } else {
- Log.d(TAG, "onBluetoothServiceUp: cb is null!!!");
- }
- } catch (Exception e) { Log.e(TAG,"",e);}
- }
- }
- }</p><p> public void onBluetoothServiceDown() {
- if (VDBG) Log.d(TAG, "onBluetoothServiceDown: " + mService);
- synchronized (mManagerCallback) {
- mService = null;
- for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){
- try {
- if (cb != null) {
- cb.onBluetoothServiceDown();
- } else {
- Log.d(TAG, "onBluetoothServiceDown: cb is null!!!");
- }
- } catch (Exception e) { Log.e(TAG,"",e);}
- }
- }
- }
- }</p>
\frameworks\base\services\java\com\android\server\BluetoothManagerService.cpp
- public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
- Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
- msg.obj = callback;
- mHandler.sendMessage(msg);
- if (DBG) Log.d(TAG,"registerAdapter start");
- synchronized(mConnection) {
- if (DBG) Log.d(TAG,"registerAdapter end");
- return mBluetooth;
- }
- }
BluetoothHandler-->handleMessage-->
- case MESSAGE_REGISTER_ADAPTER:
- {
- IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
- boolean added = mCallbacks.register(callback);
- }
最后注册到RemoteCallbackList中。
BT使能
BluetoothManagerService::
- enable-->sendEnableMsg-->mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,quietMode ? 1 : 0, 0));
- uetoothHandler
- handleMessage-->handleEnable(true)-->mBluetooth.registerCallback(mBluetoothCallback);
- sendBluetoothServiceUpCallback();
- mBluetooth.enable()
- ate 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);
- }
mBluetoothCallback将消息交给BluetoothHandler的sendMessage来处理。
- private void sendBluetoothServiceUpCallback() {
- if (!mConnection.isGetNameAddressOnly()) {
- int n = mCallbacks.beginBroadcast();
- for (int i=0; i <n;i++) {
- try {
- mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
- } catch (RemoteException e) {
- }
- }
- mCallbacks.finishBroadcast();
- }
- }
通知BluetoothAdapter,Adapter service is up
- private void sendBluetoothServiceUpCallback() {
- if (!mConnection.isGetNameAddressOnly()) {
- int n = mCallbacks.beginBroadcast();
- for (int i=0; i <n;i++) {
- try {
- mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
- } catch (RemoteException e) {
- Log.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
- }
- }
- mCallbacks.finishBroadcast();
- }
- }
mCallbacks.getBroadcastItem(i)用来获取对对应IBluetoothManagerCallback,这是是指BluetoothAdapter::mManagerCallback,因此调用的是BluetoothAdapter的onBluetoothServiceUp:
- public void onBluetoothServiceUp(IBluetooth bluetoothService) {
- if (VDBG) Log.d(TAG, "onBluetoothServiceUp: " + bluetoothService);
- synchronized (mManagerCallback) {
- mService = bluetoothService;
- for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){
- try {
- if (cb != null) {
- cb.onBluetoothServiceUp(bluetoothService);
- } else {
- Log.d(TAG, "onBluetoothServiceUp: cb is null!!!");
- }
- } catch (Exception e) { Log.e(TAG,"",e);}
- }
- }
- }
到此为止,还没有对BT硬件的操作,现在回到BluetoothManagerService的handleEnable,下一步调用了mBluetooth.enable(),最终是调用IBluetooth的enable。
以上我们只看到了IBluetooth的客户端代码,服务端在哪儿呢?看AdapterService的定义。
- public class AdapterService extends Service{
- static {
- classInitNative();
- }
- private static class AdapterServiceBinder extends IBluetooth.Stub
- }
classInitNative被声明成Native方法,直接调用com/android/bluetooth/btservice/AdapterService的classInitNative
\packages\apps\Bluetooth\jni\com_android_bluetooth_btservice_AdapterService.cpp
- <p>static void classInitNative(JNIEnv* env, jclass clazz) {
- int err;
- hw_module_t* module;</p><p> jclass jniCallbackClass =
- env->FindClass("com/android/bluetooth/btservice/JniCallbacks");
- sJniCallbacksField = env->GetFieldID(clazz, "mJniCallbacks",
- "Lcom/android/bluetooth/btservice/JniCallbacks;");</p><p> method_stateChangeCallback = env->GetMethodID(jniCallbackClass, "stateChangeCallback", "(I)V");</p><p> method_adapterPropertyChangedCallback = env->GetMethodID(jniCallbackClass,
- "adapterPropertyChangedCallback",
- "([I[[B)V");
- method_discoveryStateChangeCallback = env->GetMethodID(jniCallbackClass,
- "discoveryStateChangeCallback", "(I)V");</p><p> method_devicePropertyChangedCallback = env->GetMethodID(jniCallbackClass,
- "devicePropertyChangedCallback",
- "([B[I[[B)V");
- method_deviceFoundCallback = env->GetMethodID(jniCallbackClass, "deviceFoundCallback", "([B)V");
- method_pinRequestCallback = env->GetMethodID(jniCallbackClass, "pinRequestCallback",
- "([B[BI)V");
- method_sspRequestCallback = env->GetMethodID(jniCallbackClass, "sspRequestCallback",
- "([B[BIII)V");</p><p> method_bondStateChangeCallback = env->GetMethodID(jniCallbackClass,
- "bondStateChangeCallback", "(I[BI)V");</p><p> method_aclStateChangeCallback = env->GetMethodID(jniCallbackClass,
- "aclStateChangeCallback", "(I[BI)V");
- char value[PROPERTY_VALUE_MAX];
- property_get("bluetooth.mock_stack", value, "");</p><p> const char *id = (strcmp(value, "1")? BT_STACK_MODULE_ID : BT_STACK_TEST_MODULE_ID);</p><p> err = hw_get_module(id, (hw_module_t const**)&module);</p><p> if (err == 0) {
- hw_device_t* abstraction;
- err = module->methods->open(module, id, &abstraction);
- if (err == 0) {
- bluetooth_module_t* btStack = (bluetooth_module_t *)abstraction;
- sBluetoothInterface = btStack->get_bluetooth_interface();
- } else {
- ALOGE("Error while opening Bluetooth library");
- }
- } else {
- ALOGE("No Bluetooth Library found");
- }
- }</p>这里主要是得到了sBluetoothInterface
AdapterService继承至Service,有一个内部类继承IBluetooth.Stub,这便是Bluetooth的服务端了。因此在AdapterService中必定有Bluetooth的服务端的具体实现。
AdapterServiceBinder::enable
- public boolean enable() {
- if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
- (!Utils.checkCaller())) {
- Log.w(TAG,"enable(): not allowed for non-active user and non system user");
- return false;
- AdapterService service = getService();
- if (service == null) return false;
- return service.enable();
- }
再看一下AdapterService的onCreate,这里调用了AdapterServiceBinder的构造
public void onCreate() {
super.onCreate();
mBinder = new AdapterServiceBinder(this);
mAdapterProperties = new AdapterProperties(this);
mAdapterStateMachine = AdapterState.make(this, mAdapterProperties);
mJniCallbacks = new JniCallbacks(mAdapterStateMachine, mAdapterProperties);
initNative();
mNativeAvailable=true;
mCallbacks = new RemoteCallbackList<IBluetoothCallback>();
//Load the name and address
getAdapterPropertyNative(AbstractionLayer.BT_PROPERTY_BDADDR);
getAdapterPropertyNative(AbstractionLayer.BT_PROPERTY_BDNAME);
}
service.enable()的的service是AdapterService,下一步是AdapterService的enable
- public synchronized boolean enable(boolean quietMode) {
- enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
- "Need BLUETOOTH ADMIN permission");
- if (DBG)debugLog("Enable called with quiet mode status = " + mQuietmode);
- mQuietmode = quietMode;
- Message m =
- mAdapterStateMachine.obtainMessage(AdapterState.USER_TURN_ON);
- mAdapterStateMachine.sendMessage(m);
- return true;
- }
123456789101234567891012345678910
- mAdapterStateMachine.sendMessage(m)
- 状态转换:
OffState::USER_TURN_ON ---> processMessage::STARTED ---> processMessage::ENABLED_READY
在processMessage::STARTED 状态时调用mAdapterService.enableNative--》调用JNI方法
- static jboolean enableNative(JNIEnv* env, jobject obj) {
- jboolean result = JNI_FALSE;
- if (!sBluetoothInterface) return result;
- int ret = sBluetoothInterface->enable();
- result = (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
- return result;
- }
- struct hw_module_t HAL_MODULE_INFO_SYM = {
- .tag = HARDWARE_MODULE_TAG,
- .version_major = 1,
- .version_minor = 0,
- .id = BT_HARDWARE_MODULE_ID,
- .name = "Bluetooth Stack",
- .author = "The Android Open Source Project",
- .methods = &bt_stack_module_methods
- };
- static int enable( void )
- {
- /* sanity check */
- if (interface_ready() == FALSE)
- return BT_STATUS_NOT_READY;
- return btif_enable_bluetooth();
- }
E:\BOX_4.2\external\bluetooth\bluedroid\btif\src\btif_core.c
- bt_status_t btif_enable_bluetooth(void)
- {
- BTIF_TRACE_DEBUG0("BTIF ENABLE BLUETOOTH");
- if (btif_core_state != BTIF_CORE_STATE_DISABLED)
- {
- ALOGD("not disabled\n");
- return BT_STATUS_DONE;
- }
- btif_core_state = BTIF_CORE_STATE_ENABLING;
- /* Create the GKI tasks and run them */
- bte_main_enable(btif_local_bd_addr.address);
- return BT_STATUS_SUCCESS;
- }
bte_main_enable-->bt_hc_if->set_power
bt_hc_if是HCI层接口
\external\bluetooth\bluedroid\hci\src\bt_hci_bdroid.c
- static const bt_hc_interface_t bluetoothHCLibInterface = {
- sizeof(bt_hc_interface_t),
- init,
- set_power,
- lpm,
- preload,
- postload,
- transmit_buf,
- set_rxflow,
- logging,
- cleanup
- };
![](https://img-my.csdn.net/uploads/201304/16/1366103944_3465.jpg)