当前位置:   article > 正文

Android蓝牙使能流程图(Android Bluetooth enable) -- java & jni层_config_hearing_aid_profile_supported

config_hearing_aid_profile_supported

在介绍Android enable流程之前,我们首先来看下Android的流程图

以上图示是android8以上的,主要跟Android8之前的架构在于Bluetooth stack跟vendor层之间增加一层HIDL,主要是抽象硬件层的作用

OK,回归主题,我们来看下Android的enable流程,首先上一张架构图

另外声明下:我们做了一些列的蓝牙教程(包括视频)。我们会以连载的方式持续更新,内容如下:

本专栏文章我们会以连载的方式持续更新,本专栏计划更新内容如下:

第一篇:蓝牙综合介绍 ,主要介绍蓝牙的一些概念,产生背景,发展轨迹,市面蓝牙介绍,以及蓝牙开发板介绍。

第二篇:Transport层介绍,主要介绍蓝牙协议栈跟蓝牙芯片之前的硬件传输协议,比如基于UART的H4,H5,BCSP,基于USB的H2等

第三篇:传统蓝牙controller介绍,主要介绍传统蓝牙芯片的介绍,包括射频层(RF),基带层(baseband),链路管理层(LMP)等

第四篇:传统蓝牙host介绍,主要介绍传统蓝牙的协议栈,比如HCI,L2CAP,SDP,RFCOMM,HFP,SPP,HID,AVDTP,AVCTP,A2DP,AVRCP,OBEX,PBAP,MAP等等一系列的协议吧。

第五篇:低功耗蓝牙controller介绍,主要介绍低功耗蓝牙芯片,包括物理层(PHY),链路层(LL)

第六篇:低功耗蓝牙host介绍,低功耗蓝牙协议栈的介绍,包括HCI,L2CAP,ATT,GATT,SM等

第七篇:蓝牙芯片介绍,主要介绍一些蓝牙芯片的初始化流程,基于HCI vendor command的扩展

第八篇:附录,主要介绍以上常用名词的介绍以及一些特殊流程的介绍等。

另外,开发板如下所示,对于想学习蓝牙协议栈的最好人手一套。以便更好的学习蓝牙协议栈,相信我,学完这一套视频你将拥有修改任何协议栈的能力(比如Linux下的bluez,Android下的bluedroid)。

-------------------------------------------------------------------------------------------------------------------------

蓝牙视频教程(跟韦东山老师合作)https://item.taobao.com/item.htm?spm=a1z10.5-c-s.w4002-22329603914.10.77201fc98qgCWh&id=679276693032

蓝牙交流扣扣群:970324688

Github代码:GitHub - sj15712795029/bluetooth_stack: 这是一个开源的双模蓝牙协议栈(bluetooth.stack)(btstack),可以运行在STM32,Linux.,包含HCI,L2CAP,SDP,RFCOMM,HFP,SPP,A2DP,AVRCP,AVDTP,AVCTP,OBEX,PBAP等协议,后续会继续维护,以达到商用的目的

入手开发板:https://shop220811498.taobao.com/category-1542116976.htm?spm=a1z10.5-c-s.w4010-22329603913.7.39ca7dbe2EA0K3&search=y&catName=%C0%B6%D1%C0%BF%AA%B7%A2%B0%E5#bd

蓝牙学习目录一篇文章足够你学习蓝牙技术,提供史上最全的蓝牙技术(传统蓝牙/低功耗蓝牙)文章总结,文档下载总结(2020/12/11更新)_Wireless_Link的博客-CSDN博客_蓝牙eir

--------------------------------------------------------------------------------------------------------------------------

步骤1:开机会启动SystemServer类的main函数

在Android系统启动过程中,SystemServer是第一个被启动的进程。当Android设备被开机后,内核会创建一个名为init的进程,init进程会启动Zygote进程,Zygote进程会启动SystemServer进程。因此,SystemServer是整个Android系统启动的核心进程,它负责初始化并启动大部分系统服务和应用程序,是整个Android系统的主要启动入口。

具体来说,SystemServer主要完成以下几个任务:

  • 启动和初始化系统服务:SystemServer会启动和初始化大部分系统服务,例如ActivityManagerService、WindowManagerService、PackageManagerService、PowerManagerService等等。这些服务会在启动过程中被创建并注册到系统服务中心,供其他应用程序和服务调用。

  • 启动和初始化核心应用程序:SystemServer会启动和初始化Android系统中的核心应用程序,例如SystemUI、Settings等等。这些应用程序会在启动过程中被创建并运行,提供各种用户界面和功能。

  • 加载和初始化系统属性:SystemServer会加载和初始化/system/build.prop文件中定义的系统属性,例如设备型号、厂商信息等等。这些属性可以在系统运行时被访问和修改。

  • 启动Adb守护进程:SystemServer会启动Adb守护进程,使得开发者可以通过adb工具来访问设备。

总之,SystemServer是整个Android系统启动过程中的核心进程,负责启动和初始化大部分系统服务和应用程序,为整个系统的运行提供基础支持。SystemServer的启动时间通常在内核启动之后的几秒钟内,具体时间取决于设备的硬件性能和系统配置。

  1. /**
  2. * The main entry point from zygote.
  3. */
  4. public static void main(String[] args) {
  5. new SystemServer().run();
  6. }

SystemServer().run();执行startOtherServices(t);

然后startOtherServices(t);执行如下代码,开启Bluetooth service类

  1. private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
  2. ...
  3. if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
  4. Slog.i(TAG, "No Bluetooth Service (factory test)");
  5. } else if (!context.getPackageManager().hasSystemFeature
  6. (PackageManager.FEATURE_BLUETOOTH)) {
  7. Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");
  8. } else {
  9. t.traceBegin("StartBluetoothService");
  10. mSystemServiceManager.startService(BluetoothService.class);
  11. t.traceEnd();
  12. }
  13. ...
  14. }

步骤2:BluetoothService构造函数中执行创建BluetoothManagerService

mBluetoothManagerService = new BluetoothManagerService(context);

  1. BluetoothManagerService(Context context) {
  2. Slog.e(TAG, "new BluetoothManagerService");
  3. // BluetoothManagerService的私有类,主要用于处理一些message
  4. mHandler = new BluetoothHandler(IoThread.get().getLooper());
  5. mContext = context;
  6. mWirelessConsentRequired = context.getResources()
  7. .getBoolean(com.android.internal.R.bool.config_wirelessConsentRequired);
  8. mCrashes = 0;
  9. mBluetooth = null;
  10. mBluetoothBinder = null;
  11. mBluetoothGatt = null;
  12. mBinding = false;
  13. mUnbinding = false;
  14. mEnable = false;
  15. mState = BluetoothAdapter.STATE_OFF;
  16. mQuietEnableExternal = false;
  17. mEnableExternal = false;
  18. mAddress = null;
  19. mName = null;
  20. mErrorRecoveryRetryCounter = 0;
  21. mContentResolver = context.getContentResolver();
  22. // Observe BLE scan only mode settings change.
  23. registerForBleScanModeChange();
  24. mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
  25. mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
  26. mIsHearingAidProfileSupported = context.getResources()
  27. .getBoolean(com.android.internal.R.bool.config_hearing_aid_profile_supported);
  28. // TODO: We need a more generic way to initialize the persist keys of FeatureFlagUtils
  29. String value = SystemProperties.get(FeatureFlagUtils.PERSIST_PREFIX + FeatureFlagUtils.HEARING_AID_SETTINGS);
  30. if (!TextUtils.isEmpty(value)) {
  31. boolean isHearingAidEnabled = Boolean.parseBoolean(value);
  32. Log.v(TAG, "set feature flag HEARING_AID_SETTINGS to " + isHearingAidEnabled);
  33. FeatureFlagUtils.setEnabled(context, FeatureFlagUtils.HEARING_AID_SETTINGS, isHearingAidEnabled);
  34. if (isHearingAidEnabled && !mIsHearingAidProfileSupported) {
  35. // Overwrite to enable support by FeatureFlag
  36. mIsHearingAidProfileSupported = true;
  37. }
  38. }
  39. IntentFilter filter = new IntentFilter();
  40. filter.addAction(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
  41. filter.addAction(BluetoothAdapter.ACTION_BLUETOOTH_ADDRESS_CHANGED);
  42. filter.addAction(Intent.ACTION_SETTING_RESTORED);
  43. filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
  44. mContext.registerReceiver(mReceiver, filter);
  45. loadStoredNameAndAddress();
  46. if (isBluetoothPersistedStateOn()) {
  47. if (DBG) {
  48. Slog.d(TAG, "Startup: Bluetooth persisted state is ON.");
  49. }
  50. mEnableExternal = true;
  51. }
  52. String airplaneModeRadios =
  53. Settings.Global.getString(mContentResolver, Settings.Global.AIRPLANE_MODE_RADIOS);
  54. if (airplaneModeRadios == null || airplaneModeRadios.contains(
  55. Settings.Global.RADIO_BLUETOOTH)) {
  56. mBluetoothAirplaneModeListener = new BluetoothAirplaneModeListener(
  57. this, IoThread.get().getLooper(), context);
  58. }
  59. int systemUiUid = -1;
  60. // Check if device is configured with no home screen, which implies no SystemUI.
  61. boolean noHome = mContext.getResources().getBoolean(R.bool.config_noHomeScreen);
  62. if (!noHome) {
  63. PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
  64. systemUiUid = pm.getPackageUid(pm.getSystemUiServiceComponent().getPackageName(),
  65. MATCH_SYSTEM_ONLY, USER_SYSTEM);
  66. }
  67. if (systemUiUid >= 0) {
  68. Slog.d(TAG, "Detected SystemUiUid: " + Integer.toString(systemUiUid));
  69. } else {
  70. // Some platforms, such as wearables do not have a system ui.
  71. Slog.w(TAG, "Unable to resolve SystemUI's UID.");
  72. }
  73. mSystemUiUid = systemUiUid;
  74. }

步骤3:启动默认用户调用的方法处理

  1. public void onSwitchUser(int userHandle) {
  2. if (!mInitialized) {
  3. initialize();
  4. } else {
  5. mBluetoothManagerService.handleOnSwitchUser(userHandle);
  6. }
  7. }

onSwitchUser 是 Android 框架中的一个回调方法,用于在用户切换时接收通知。当有多个用户在同一个设备上使用时,可以使用此方法来执行一些特定于用户的操作,例如切换到其它用户时保存当前用户的状态并加载新用户的数据。

在 Android 系统中,只有在设备启用多用户功能并启用多个用户帐户时才会调用此方法。在单用户设备上,该方法不会被调用。

当一个用户从其它用户切换到当前用户时,系统会调用 onSwitchUser 方法。

当设备启动时,如果已经启用了多用户功能,则系统会自动创建一个默认的用户,并在该用户的环境下启动应用程序。此时,onSwitchUser 方法也会被调用,此时传递给方法的 userId 参数为默认用户的 ID。

备注:该方法已经在 Android 12 中被标记为过时。因此,在新的应用程序中,应该避免使用该方法,而应该考虑使用更现代的 Android 架构组件或 API 来实现多用户管理和数据保护。

  1. private void initialize() {
  2. if (!mInitialized) {
  3. mBluetoothManagerService.handleOnBootPhase();
  4. mInitialized = true;
  5. }
  6. }
  1. public void handleOnBootPhase() {
  2. ...
  3. final boolean isSafeMode = mContext.getPackageManager().isSafeMode();
  4. if (mEnableExternal && isBluetoothPersistedStateOnBluetooth() && !isSafeMode) {
  5. if (DBG) {
  6. Slog.d(TAG, "Auto-enabling Bluetooth.");
  7. }
  8. //调用
  9. sendEnableMsg(mQuietEnableExternal,
  10. BluetoothProtoEnums.ENABLE_DISABLE_REASON_SYSTEM_BOOT,
  11. mContext.getPackageName());
  12. }
  13. ....
  14. }

步骤4:BluetoothManagerService.java处理enable

  1. private void sendEnableMsg(boolean quietMode, int reason, String packageName) {
  2. mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE, quietMode ? 1 : 0, 0));
  3. addActiveLog(reason, packageName, true);
  4. mLastEnabledTime = SystemClock.elapsedRealtime();
  5. }
  1. public void handleMessage(Message msg)
  2. {
  3. switch (msg.what)
  4. {
  5. case MESSAGE_ENABLE:
  6. handleEnable(mQuietEnable);
  7. break;
  8. }
  9. }
  1. private void handleEnable(boolean quietMode)
  2. {
  3. ...
  4. Intent i = new Intent(IBluetooth.class.getName());
  5. if (!doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
  6. UserHandle.CURRENT)) {
  7. mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
  8. } else {
  9. mBinding = true;
  10. }
  11. ...
  12. }

bond后会调用这个函数onServiceConnected

  1. private class BluetoothServiceConnection implements ServiceConnection {
  2. public void onServiceConnected(ComponentName componentName, IBinder service) {
  3. String name = componentName.getClassName();
  4. if (DBG) {
  5. Slog.d(TAG, "BluetoothServiceConnection: " + name);
  6. }
  7. Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
  8. if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
  9. msg.arg1 = SERVICE_IBLUETOOTH;
  10. } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
  11. msg.arg1 = SERVICE_IBLUETOOTHGATT;
  12. } else {
  13. Slog.e(TAG, "Unknown service connected: " + name);
  14. return;
  15. }
  16. msg.obj = service;
  17. mHandler.sendMessage(msg);
  18. }
  19. public void onServiceDisconnected(ComponentName componentName) {
  20. // Called if we unexpectedly disconnect.
  21. String name = componentName.getClassName();
  22. if (DBG) {
  23. Slog.d(TAG, "BluetoothServiceConnection, disconnected: " + name);
  24. }
  25. Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
  26. if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
  27. msg.arg1 = SERVICE_IBLUETOOTH;
  28. } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
  29. msg.arg1 = SERVICE_IBLUETOOTHGATT;
  30. } else {
  31. Slog.e(TAG, "Unknown service disconnected: " + name);
  32. return;
  33. }
  34. mHandler.sendMessage(msg);
  35. }
  36. }
  1. public void handleMessage(Message msg)
  2. {
  3. switch (msg.what)
  4. {
  5. case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
  6. ...
  7. mBluetooth.registerCallback(mBluetoothCallback);
  8. ...
  9. sendBluetoothServiceUpCallback();
  10. ...
  11. mBluetooth.enable(mQuietEnable);
  12. break;
  13. }
  14. }

步骤5:AdapterService.java处理enable

注意在里面还有一个AdapterServiceBinder的类,不是这个类下面的enable

  1. public synchronized boolean enable(boolean quietMode) {
  2. // Enforce the user restriction for disallowing Bluetooth if it was set.
  3. if (mUserManager.hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM)) {
  4. debugLog("enable() called when Bluetooth was disallowed");
  5. return false;
  6. }
  7. Log.e(TAG, "AdapterService enable");
  8. debugLog("enable() - Enable called with quiet mode status = " + quietMode);
  9. mQuietmode = quietMode;
  10. mAdapterStateMachine.sendMessage(AdapterState.BLE_TURN_ON);
  11. return true;
  12. }

这个会触发status machine,会调用到OffState中processMessage

  1. public boolean processMessage(Message msg) {
  2. switch (msg.what) {
  3. case BLE_TURN_ON:
  4. transitionTo(mTurningBleOnState);
  5. break;
  6. default:
  7. infoLog("Unhandled message - " + messageString(msg.what));
  8. return false;
  9. }
  10. return true;
  11. }

然后进入到TurningBleOnState类中的enter

  1. public void enter() {
  2. super.enter();
  3. sendMessageDelayed(BLE_START_TIMEOUT, BLE_START_TIMEOUT_DELAY);
  4. mAdapterService.bringUpBle();
  5. }
  1. void bringUpBle() {
  2. ...
  3. //Start Gatt service
  4. setProfileServiceState(GattService.class, BluetoothAdapter.STATE_ON);
  5. }

开启gattservice服务

另外,ProfileService的状态改变会触发AdapterService的onProfileServiceStateChanged

  1. public void onProfileServiceStateChanged(ProfileService profile, int state) {
  2. if (state != BluetoothAdapter.STATE_ON && state != BluetoothAdapter.STATE_OFF) {
  3. throw new IllegalArgumentException(BluetoothAdapter.nameForState(state));
  4. }
  5. Message m = mHandler.obtainMessage(MESSAGE_PROFILE_SERVICE_STATE_CHANGED);
  6. m.obj = profile;
  7. m.arg1 = state;
  8. mHandler.sendMessage(m);
  9. }
  1. private void processProfileServiceStateChanged(ProfileService profile, int state) {
  2. switch (state) {
  3. case BluetoothAdapter.STATE_ON:
  4. if (!mRegisteredProfiles.contains(profile)) {
  5. Log.e(TAG, profile.getName() + " not registered (STATE_ON).");
  6. return;
  7. }
  8. if (mRunningProfiles.contains(profile)) {
  9. Log.e(TAG, profile.getName() + " already running.");
  10. return;
  11. }
  12. mRunningProfiles.add(profile);
  13. if (GattService.class.getSimpleName().equals(profile.getName())) {
  14. Log.e(TAG, "processProfileServiceStateChanged enableNative");
  15. // 这个地方就是调用libjni.so的方法,通过jni native调用
  16. enableNative();
  17. } else if (mRegisteredProfiles.size() == Config.getSupportedProfiles().length
  18. && mRegisteredProfiles.size() == mRunningProfiles.size()) {
  19. mAdapterProperties.onBluetoothReady();
  20. updateUuids();
  21. setBluetoothClassFromConfig();
  22. initProfileServices();
  23. getAdapterPropertyNative(AbstractionLayer.BT_PROPERTY_LOCAL_IO_CAPS);
  24. getAdapterPropertyNative(AbstractionLayer.BT_PROPERTY_LOCAL_IO_CAPS_BLE);
  25. mAdapterStateMachine.sendMessage(AdapterState.BREDR_STARTED);
  26. }
  27. break;
  28. default:
  29. Log.e(TAG, "Unhandled profile state: " + state);
  30. }
  31. }

NOTED:能够直接调用到libbluetooth_jni.so的原因是AdapterApp 类在启动的时候加载了

  1. public class AdapterApp extends Application
  2. {
  3. private static final String TAG = "BluetoothAdapterApp";
  4. private static final boolean DBG = false;
  5. //For Debugging only
  6. private static int sRefCount = 0;
  7. static {
  8. if (DBG) {
  9. Log.d(TAG, "Loading JNI Library");
  10. }
  11. System.loadLibrary("bluetooth_jni");
  12. }
  13. ...
  14. }

然后这个动作会触发com_android_bluetooth_btservice_adapterService.cpp中的

  1. jint JNI_OnLoad(JavaVM* jvm, void* reserved) {
  2. JNIEnv* e;
  3. int status;
  4. ALOGE("Bluetooth Adapter Service : loading JNI\n");
  5. ALOGV("Bluetooth Adapter Service : loading JNI\n");
  6. // Check JNI version
  7. if (jvm->GetEnv((void**)&e, JNI_VERSION_1_6)) {
  8. ALOGE("JNI version mismatch error");
  9. return JNI_ERR;
  10. }
  11. status = android::register_com_android_bluetooth_btservice_AdapterService(e);
  12. if (status < 0) {
  13. ALOGE("jni adapter service registration failure, status: %d", status);
  14. return JNI_ERR;
  15. }
  16. status =
  17. android::register_com_android_bluetooth_btservice_BluetoothKeystore(e);
  18. if (status < 0) {
  19. ALOGE("jni BluetoothKeyStore registration failure: %d", status);
  20. return JNI_ERR;
  21. }
  22. status = android::register_com_android_bluetooth_hfp(e);
  23. if (status < 0) {
  24. ALOGE("jni hfp registration failure, status: %d", status);
  25. return JNI_ERR;
  26. }
  27. status = android::register_com_android_bluetooth_hfpclient(e);
  28. if (status < 0) {
  29. ALOGE("jni hfp client registration failure, status: %d", status);
  30. return JNI_ERR;
  31. }
  32. status = android::register_com_android_bluetooth_a2dp(e);
  33. if (status < 0) {
  34. ALOGE("jni a2dp source registration failure: %d", status);
  35. return JNI_ERR;
  36. }
  37. status = android::register_com_android_bluetooth_a2dp_sink(e);
  38. if (status < 0) {
  39. ALOGE("jni a2dp sink registration failure: %d", status);
  40. return JNI_ERR;
  41. }
  42. status = android::register_com_android_bluetooth_avrcp_target(e);
  43. if (status < 0) {
  44. ALOGE("jni new avrcp target registration failure: %d", status);
  45. }
  46. status = android::register_com_android_bluetooth_avrcp_controller(e);
  47. if (status < 0) {
  48. ALOGE("jni avrcp controller registration failure: %d", status);
  49. return JNI_ERR;
  50. }
  51. status = android::register_com_android_bluetooth_hid_host(e);
  52. if (status < 0) {
  53. ALOGE("jni hid registration failure: %d", status);
  54. return JNI_ERR;
  55. }
  56. status = android::register_com_android_bluetooth_hid_device(e);
  57. if (status < 0) {
  58. ALOGE("jni hidd registration failure: %d", status);
  59. return JNI_ERR;
  60. }
  61. status = android::register_com_android_bluetooth_pan(e);
  62. if (status < 0) {
  63. ALOGE("jni pan registration failure: %d", status);
  64. return JNI_ERR;
  65. }
  66. status = android::register_com_android_bluetooth_gatt(e);
  67. if (status < 0) {
  68. ALOGE("jni gatt registration failure: %d", status);
  69. return JNI_ERR;
  70. }
  71. status = android::register_com_android_bluetooth_sdp(e);
  72. if (status < 0) {
  73. ALOGE("jni sdp registration failure: %d", status);
  74. return JNI_ERR;
  75. }
  76. status = android::register_com_android_bluetooth_hearing_aid(e);
  77. if (status < 0) {
  78. ALOGE("jni hearing aid registration failure: %d", status);
  79. return JNI_ERR;
  80. }
  81. return JNI_VERSION_1_6;
  82. }

步骤6:bluetooth jni的enableNative处理

  1. static jboolean enableNative(JNIEnv* env, jobject obj) {
  2. ALOGV("%s", __func__);
  3. if (!sBluetoothInterface) return JNI_FALSE;
  4. int ret = sBluetoothInterface->enable();
  5. return (ret == BT_STATUS_SUCCESS || ret == BT_STATUS_DONE) ? JNI_TRUE
  6. : JNI_FALSE;
  7. }

其中sBluetoothInterface 是hal接口,定义如下:

  1. typedef struct {
  2. /** set to sizeof(bt_interface_t) */
  3. size_t size;
  4. /**
  5. * Opens the interface and provides the callback routines
  6. * to the implemenation of this interface.
  7. * The |is_atv| flag indicates whether the local device is an Android TV
  8. */
  9. int (*init)(bt_callbacks_t* callbacks, bool is_atv);
  10. /** Enable Bluetooth. */
  11. int (*enable)(bool guest_mode);
  12. /** Disable Bluetooth. */
  13. int (*disable)(void);
  14. /** Closes the interface. */
  15. void (*cleanup)(void);
  16. /** Get all Bluetooth Adapter properties at init */
  17. int (*get_adapter_properties)(void);
  18. /** Get Bluetooth Adapter property of 'type' */
  19. int (*get_adapter_property)(bt_property_type_t type);
  20. /** Set Bluetooth Adapter property of 'type' */
  21. /* Based on the type, val shall be one of
  22. * RawAddress or bt_bdname_t or bt_scanmode_t etc
  23. */
  24. int (*set_adapter_property)(const bt_property_t *property);
  25. /** Get all Remote Device properties */
  26. int (*get_remote_device_properties)(RawAddress *remote_addr);
  27. /** Get Remote Device property of 'type' */
  28. int (*get_remote_device_property)(RawAddress *remote_addr,
  29. bt_property_type_t type);
  30. /** Set Remote Device property of 'type' */
  31. int (*set_remote_device_property)(RawAddress *remote_addr,
  32. const bt_property_t *property);
  33. /** Get Remote Device's service record for the given UUID */
  34. int (*get_remote_service_record)(const RawAddress& remote_addr,
  35. const bluetooth::Uuid& uuid);
  36. /** Start SDP to get remote services */
  37. int (*get_remote_services)(RawAddress *remote_addr);
  38. /** Start Discovery */
  39. int (*start_discovery)(void);
  40. /** Cancel Discovery */
  41. int (*cancel_discovery)(void);
  42. /** Create Bluetooth Bonding */
  43. int (*create_bond)(const RawAddress *bd_addr, int transport);
  44. /** Create Bluetooth Bond using out of band data */
  45. int (*create_bond_out_of_band)(const RawAddress *bd_addr, int transport,
  46. const bt_out_of_band_data_t *oob_data);
  47. /** Remove Bond */
  48. int (*remove_bond)(const RawAddress *bd_addr);
  49. /** Cancel Bond */
  50. int (*cancel_bond)(const RawAddress *bd_addr);
  51. /**
  52. * Get the connection status for a given remote device.
  53. * return value of 0 means the device is not connected,
  54. * non-zero return status indicates an active connection.
  55. */
  56. int (*get_connection_state)(const RawAddress *bd_addr);
  57. /** BT Legacy PinKey Reply */
  58. /** If accept==FALSE, then pin_len and pin_code shall be 0x0 */
  59. int (*pin_reply)(const RawAddress *bd_addr, uint8_t accept,
  60. uint8_t pin_len, bt_pin_code_t *pin_code);
  61. /** BT SSP Reply - Just Works, Numeric Comparison and Passkey
  62. * passkey shall be zero for BT_SSP_VARIANT_PASSKEY_COMPARISON &
  63. * BT_SSP_VARIANT_CONSENT
  64. * For BT_SSP_VARIANT_PASSKEY_ENTRY, if accept==FALSE, then passkey
  65. * shall be zero */
  66. int (*ssp_reply)(const RawAddress *bd_addr, bt_ssp_variant_t variant,
  67. uint8_t accept, uint32_t passkey);
  68. /** Get Bluetooth profile interface */
  69. const void* (*get_profile_interface) (const char *profile_id);
  70. /** Bluetooth Test Mode APIs - Bluetooth must be enabled for these APIs */
  71. /* Configure DUT Mode - Use this mode to enter/exit DUT mode */
  72. int (*dut_mode_configure)(uint8_t enable);
  73. /* Send any test HCI (vendor-specific) command to the controller. Must be in DUT Mode */
  74. int (*dut_mode_send)(uint16_t opcode, uint8_t *buf, uint8_t len);
  75. /** BLE Test Mode APIs */
  76. /* opcode MUST be one of: LE_Receiver_Test, LE_Transmitter_Test, LE_Test_End */
  77. int (*le_test_mode)(uint16_t opcode, uint8_t *buf, uint8_t len);
  78. /** Sets the OS call-out functions that bluedroid needs for alarms and wake locks.
  79. * This should be called immediately after a successful |init|.
  80. */
  81. int (*set_os_callouts)(bt_os_callouts_t *callouts);
  82. /** Read Energy info details - return value indicates BT_STATUS_SUCCESS or BT_STATUS_NOT_READY
  83. * Success indicates that the VSC command was sent to controller
  84. */
  85. int (*read_energy_info)();
  86. /**
  87. * Native support for dumpsys function
  88. * Function is synchronous and |fd| is owned by caller.
  89. * |arguments| are arguments which may affect the output, encoded as
  90. * UTF-8 strings.
  91. */
  92. void (*dump)(int fd, const char **arguments);
  93. /**
  94. * Clear /data/misc/bt_config.conf and erase all stored connections
  95. */
  96. int (*config_clear)(void);
  97. /**
  98. * Clear (reset) the dynamic portion of the device interoperability database.
  99. */
  100. void (*interop_database_clear)(void);
  101. /**
  102. * Add a new device interoperability workaround for a remote device whose
  103. * first |len| bytes of the its device address match |addr|.
  104. * NOTE: |feature| has to match an item defined in interop_feature_t (interop.h).
  105. */
  106. void (*interop_database_add)(uint16_t feature, const RawAddress *addr, size_t len);
  107. } bt_interface_t;

这个enable是调用libbluetooth.so中的enable,也就是bluedroid bluetooth.cc或者android8之前的bluetooth.c

  1. static int enable() {
  2. if (!interface_ready()) return BT_STATUS_NOT_READY;
  3. stack_manager_get_interface()->start_up_stack_async();
  4. return BT_STATUS_SUCCESS;
  5. }

然后就是走bluedroid流程了,host的初始化流程可以看我协议栈的其他文章

步骤7:底层bluedroid enable成功后回调处理

bluedroid底层enable跟controller交互成功后,调用这个函数,通过HAL_CBACK回调到bt service apk的jni

  1. static void event_signal_stack_up(UNUSED_ATTR void* context) {
  2. // Notify BTIF connect queue that we've brought up the stack. It's
  3. // now time to dispatch all the pending profile connect requests.
  4. btif_queue_connect_next();
  5. HAL_CBACK(bt_hal_cbacks, adapter_state_changed_cb, BT_STATE_ON);
  6. }

思考:为什么能调用到callback呢?

是因为adapterService 服务启动的时候调用到onCreate方法,里面有

  1. public void onCreate() {
  2. super.onCreate();
  3. debugLog("onCreate()");
  4. ...
  5. // 调用jni的方法
  6. initNative(isGuest(), isNiapMode(), configCompareResult, isAtvDevice);
  7. ...
  8. }
  1. static bool initNative(JNIEnv* env, jobject obj, jboolean isGuest,
  2. jboolean isNiapMode, int configCompareResult,
  3. jboolean isAtvDevice) {
  4. ALOGV("%s", __func__);
  5. // 注册jni的callback到bluedroid,bluedroid有回调的时候回调用到sBluetoothCallbacks
  6. int ret = sBluetoothInterface->init(
  7. &sBluetoothCallbacks, isGuest == JNI_TRUE ? 1 : 0,
  8. isNiapMode == JNI_TRUE ? 1 : 0, configCompareResult,
  9. isAtvDevice == JNI_TRUE ? 1 : 0);
  10. if (ret != BT_STATUS_SUCCESS) {
  11. ALOGE("Error while setting the callbacks: %d\n", ret);
  12. sBluetoothInterface = NULL;
  13. return JNI_FALSE;
  14. }
  15. }

好了,回归会提,如果bluedroid enable成功后,会调用到sBluetoothCallbacks的adapter_state_change_callback函数

  1. static void adapter_state_change_callback(bt_state_t status) {
  2. ALOGE("Bluetooth adapter_state_change_callback:%d\n",status);
  3. CallbackEnv sCallbackEnv(__func__);
  4. if (!sCallbackEnv.valid()) return;
  5. ALOGV("%s: Status is: %d", __func__, status);
  6. // 通过jni的回调方法调用到AdapterService的stateChangeCallback
  7. sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_stateChangeCallback,
  8. (jint)status);
  9. }

步骤8:bt service的处理enable成功后的回调过程

  1. void stateChangeCallback(int status) {
  2. Log.e(TAG, "stateChangeCallback:"+status);
  3. if (status == AbstractionLayer.BT_STATE_OFF) {
  4. debugLog("stateChangeCallback: disableNative() completed");
  5. mAdapterStateMachine.sendMessage(AdapterState.BLE_STOPPED);
  6. } else if (status == AbstractionLayer.BT_STATE_ON) {
  7. mAdapterStateMachine.sendMessage(AdapterState.BLE_STARTED);
  8. } else {
  9. Log.e(TAG, "Incorrect status " + status + " in stateChangeCallback");
  10. }
  11. }

此时进入这个类中的processMessage处理

  1. public boolean processMessage(Message msg) {
  2. switch (msg.what) {
  3. case BLE_STARTED:
  4. transitionTo(mBleOnState);
  5. break;
  6. case BLE_START_TIMEOUT:
  7. errorLog(messageString(msg.what));
  8. transitionTo(mTurningBleOffState);
  9. break;
  10. default:
  11. infoLog("Unhandled message - " + messageString(msg.what));
  12. return false;
  13. }
  14. return true;
  15. }

迁徙到mBleOnState状态,然后处理,另外状态概念,会触发AdapterService.java中的updateAdapterState

  1. void updateAdapterState(int prevState, int newState) {
  2. mAdapterProperties.setState(newState);
  3. invalidateBluetoothGetStateCache();
  4. if (mCallbacks != null) {
  5. int n = mCallbacks.beginBroadcast();
  6. debugLog("updateAdapterState() - Broadcasting state " + BluetoothAdapter.nameForState(
  7. newState) + " to " + n + " receivers.");
  8. for (int i = 0; i < n; i++) {
  9. try {
  10. mCallbacks.getBroadcastItem(i).onBluetoothStateChange(prevState, newState);
  11. } catch (RemoteException e) {
  12. debugLog("updateAdapterState() - Callback #" + i + " failed (" + e + ")");
  13. }
  14. }
  15. mCallbacks.finishBroadcast();
  16. }
  17. ....
  18. }
  1. private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
  2. @Override
  3. public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
  4. Message msg =
  5. mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE, prevState, newState);
  6. mHandler.sendMessage(msg);
  7. }
  8. };

case处理

  1. case MESSAGE_BLUETOOTH_STATE_CHANGE: {
  2. ....
  3. bluetoothStateChangeHandler(prevState, newState);
  4. break;
  5. }
  1. private void bluetoothStateChangeHandler(int prevState, int newState) {
  2. if (newState == BluetoothAdapter.STATE_BLE_ON || newState == BluetoothAdapter.STATE_OFF) {
  3. .......
  4. continueFromBleOnState();
  5. }
  6. }
  1. private void continueFromBleOnState() {
  2. ...
  3. mBluetooth.onLeServiceUp();
  4. ...
  5. }
  1. public void onLeServiceUp() {
  2. AdapterService service = getService();
  3. if (service == null || !callerIsSystemOrActiveUser(TAG, "onLeServiceUp")) {
  4. return;
  5. }
  6. enforceBluetoothPrivilegedPermission(service);
  7. service.mAdapterStateMachine.sendMessage(AdapterState.USER_TURN_ON);
  8. }
  1. private class BleOnState extends BaseAdapterState {
  2. @Override
  3. int getStateValue() {
  4. return BluetoothAdapter.STATE_BLE_ON;
  5. }
  6. @Override
  7. public boolean processMessage(Message msg) {
  8. switch (msg.what) {
  9. case USER_TURN_ON:
  10. transitionTo(mTurningOnState);
  11. break;
  12. case BLE_TURN_OFF:
  13. transitionTo(mTurningBleOffState);
  14. break;
  15. default:
  16. infoLog("Unhandled message - " + messageString(msg.what));
  17. return false;
  18. }
  19. return true;
  20. }
  21. }

然后进入到TurningOnState class的enter处理

  1. public void enter() {
  2. super.enter();
  3. sendMessageDelayed(BREDR_START_TIMEOUT, BREDR_START_TIMEOUT_DELAY);
  4. mAdapterService.startProfileServices();
  5. }

步骤9:开启所有profile的service

  1. void startProfileServices() {
  2. ...
  3. setAllProfileServiceStates(supportedProfileServices, BluetoothAdapter.STATE_ON);
  4. }
  1. private static final ProfileConfig[] PROFILE_SERVICES_AND_FLAGS = {
  2. new ProfileConfig(HeadsetService.class, R.bool.profile_supported_hs_hfp,
  3. (1 << BluetoothProfile.HEADSET)),
  4. new ProfileConfig(A2dpService.class, R.bool.profile_supported_a2dp,
  5. (1 << BluetoothProfile.A2DP)),
  6. new ProfileConfig(A2dpSinkService.class, R.bool.profile_supported_a2dp_sink,
  7. (1 << BluetoothProfile.A2DP_SINK)),
  8. new ProfileConfig(HidHostService.class, R.bool.profile_supported_hid_host,
  9. (1 << BluetoothProfile.HID_HOST)),
  10. new ProfileConfig(PanService.class, R.bool.profile_supported_pan,
  11. (1 << BluetoothProfile.PAN)),
  12. new ProfileConfig(GattService.class, R.bool.profile_supported_gatt,
  13. (1 << BluetoothProfile.GATT)),
  14. new ProfileConfig(BluetoothMapService.class, R.bool.profile_supported_map,
  15. (1 << BluetoothProfile.MAP)),
  16. new ProfileConfig(HeadsetClientService.class, R.bool.profile_supported_hfpclient,
  17. (1 << BluetoothProfile.HEADSET_CLIENT)),
  18. new ProfileConfig(AvrcpTargetService.class, R.bool.profile_supported_avrcp_target,
  19. (1 << BluetoothProfile.AVRCP)),
  20. new ProfileConfig(AvrcpControllerService.class,
  21. R.bool.profile_supported_avrcp_controller,
  22. (1 << BluetoothProfile.AVRCP_CONTROLLER)),
  23. new ProfileConfig(SapService.class, R.bool.profile_supported_sap,
  24. (1 << BluetoothProfile.SAP)),
  25. new ProfileConfig(PbapClientService.class, R.bool.profile_supported_pbapclient,
  26. (1 << BluetoothProfile.PBAP_CLIENT)),
  27. new ProfileConfig(MapClientService.class, R.bool.profile_supported_mapmce,
  28. (1 << BluetoothProfile.MAP_CLIENT)),
  29. new ProfileConfig(HidDeviceService.class, R.bool.profile_supported_hid_device,
  30. (1 << BluetoothProfile.HID_DEVICE)),
  31. new ProfileConfig(BluetoothOppService.class, R.bool.profile_supported_opp,
  32. (1 << BluetoothProfile.OPP)),
  33. new ProfileConfig(BluetoothPbapService.class, R.bool.profile_supported_pbap,
  34. (1 << BluetoothProfile.PBAP)),
  35. new ProfileConfig(HearingAidService.class,
  36. com.android.internal.R.bool.config_hearing_aid_profile_supported,
  37. (1 << BluetoothProfile.HEARING_AID))
  38. };

因为我们之前在前面说过,开启成功后就会调用profileService change的消息,所以如下

  1. private void processProfileServiceStateChanged(ProfileService profile, int state) {
  2. switch (state) {
  3. case BluetoothAdapter.STATE_ON:
  4. ........
  5. if (GattService.class.getSimpleName().equals(profile.getName())) {
  6. enableNative();
  7. } else if (mRegisteredProfiles.size() == Config.getSupportedProfiles().length
  8. && mRegisteredProfiles.size() == mRunningProfiles.size()) { //所有ProfileService都启动完毕
  9. .......
  10. mAdapterStateMachine.sendMessage(AdapterState.BREDR_STARTED);
  11. }
  12. break;
  1. public boolean processMessage(Message msg) {
  2. switch (msg.what) {
  3. case BREDR_STARTED:
  4. transitionTo(mOnState);
  5. break;
  6. }
  7. return true;
  8. }
  1. private void bluetoothStateChangeHandler(int prevState, int newState) {
  2. ...
  3. sendBluetoothStateCallback(isUp); //广播发出数据
  4. sendBleStateChanged(prevState, newState);
  5. ...
  6. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/318627
推荐阅读
相关标签
  

闽ICP备14008679号