当蓝牙初始化完成后,接下来该做的就是注册各种服务了。首先我们来看下hs profile,该服务是用于连接蓝牙耳机。
在HeadsetService.java中,start()函数中,注册了一个HeadsetStateMachine(在诸如a2dp服务中都分别注册了一个状态机)。
private HeadsetStateMachine(HeadsetService context) {
mPhonebook = new AtPhonebook(mService, this);//控制电话拨号挂断等
mPhoneState = new HeadsetPhoneState(context, this);
****省略****
initializeNative();//下面看这个
addState(mDisconnected);
addState(mPending);
addState(mConnected);
addState(mAudioOn);
setInitialState(mDisconnected);
}
跟之前一样,initializeNative函数中应该是干正事的地方,com_android_bluetooth_hfp.cpp是他实现的地方,
tatic void initializeNative(JNIEnv *env, jobject object) {
if ( (sBluetoothHfpInterface = (bthf_interface_t *)
btInf->get_profile_interface(BT_PROFILE_HANDSFREE_ID)) == NULL) {
ALOGE("Failed to get Bluetooth Handsfree Interface");
return;
}
if ( (status = sBluetoothHfpInterface->init(&sBluetoothHfpCallbacks)) != BT_STATUS_SUCCESS) {
ALOGE("Failed to initialize Bluetooth HFP, status: %d", status);
sBluetoothHfpInterface = NULL;
return;
}
mCallbacksObj = env->NewGlobalRef(object);
}
根据调用的profile id BT_PROFILE_HANDSFREE_ID,具体使用的是btif_hf.c中的bthfInterface,sBluetoothHfpInterface则是回调的函数。
接下来来看bthfInterface中的init函数,
#if (defined(BTIF_HF_SERVICES) && (BTIF_HF_SERVICES & BTA_HFP_SERVICE_MASK))
btif_enable_service(BTA_HFP_SERVICE_ID);
#else
btif_enable_service(BTA_HSP_SERVICE_ID);
#endif
由于4.4默认只支持hsp,所以只是enable了hsp的service。
void btif_dm_execute_service_request(UINT16 event, char *p_param)
{
BOOLEAN b_enable = FALSE;
bt_status_t status;
if (event == BTIF_DM_ENABLE_SERVICE)
{
b_enable = TRUE;
}
status = btif_in_execute_service_request(*((tBTA_SERVICE_ID*)p_param), b_enable);
if (status == BT_STATUS_SUCCESS)
{
bt_property_t property;
bt_uuid_t local_uuids[BT_MAX_NUM_UUIDS];
/* Now send the UUID_PROPERTY_CHANGED event to the upper layer */
BTIF_STORAGE_FILL_PROPERTY(&property, BT_PROPERTY_UUIDS,
sizeof(local_uuids), local_uuids);
btif_storage_get_adapter_property(&property);
HAL_CBACK(bt_hal_cbacks, adapter_properties_cb,
BT_STATUS_SUCCESS, 1, &property);
}
return;
}
注册过程btif_in_execute_service_request:
bt_status_t btif_in_execute_service_request(tBTA_SERVICE_ID service_id,
BOOLEAN b_enable)
{
/* Check the service_ID and invoke the profile's BT state changed API */
switch (service_id)
{
case BTA_HFP_SERVICE_ID:
case BTA_HSP_SERVICE_ID:
{
btif_hf_execute_service(b_enable);
}break;
case BTA_A2DP_SERVICE_ID:
{
btif_av_execute_service(b_enable);
}break;
case BTA_HID_SERVICE_ID:
{
btif_hh_execute_service(b_enable);
}break;
default:
BTIF_TRACE_ERROR1("%s: Unknown service being enabled", __FUNCTION__);
return BT_STATUS_FAIL;
}
return BT_STATUS_SUCCESS;
}