Bluetooth initialization - Bluetooth process Initialization - Framework(Java)

1. Overview

  1. System_server 綁定藍(lán)牙服務(wù)時(shí)糠赦,啟動(dòng) com.android.bluetooth 進(jìn)程。
  2. 首先執(zhí)行 Application 的子類(lèi)慨畸,即 AdapterApp.java滨达,加載 libbluetooth_jni.so,加載可開(kāi)啟的 Profiles 配置信息赡盘;
  3. 隨后執(zhí)行被綁定服務(wù)類(lèi),即 AdapterService.java缰揪,初始化 JNI陨享,啟動(dòng)藍(lán)牙適配器服務(wù)。

2. Application initialization

packages/apps/Bluetooth/src/com/android/bluetooth/btservice/AdapterApp.java

public class AdapterApp extends Application {

    static {
        System.loadLibrary("bluetooth_jni");        // 1
    }

    public AdapterApp() {
        super();
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Config.init(this);                          // 2
    }
}

2.1 System.loadLibrary("bluetooth_jni")

加載 libbluetooth_jni.so 钝腺,具體如何加載抛姑,參考 System.loadLibrary(libname)

2.2 Load Supported Profiles Config

讀取配置信息,確定需要開(kāi)啟的 Profile 列表并存儲(chǔ)艳狐。
packages/apps/Bluetooth/src/com/android/bluetooth/btservice/Config.java

public class Config {

    static void init(Context ctx) {
......
        Resources resources = ctx.getResources();
        // 下面的循環(huán)遍歷中第3個(gè)條件
        List<String> enabledProfiles = getSystemConfigEnabledProfilesForPackage(ctx);

        ArrayList<Class> profiles = new ArrayList<>(PROFILE_SERVICES_AND_FLAGS.length);
        for (ProfileConfig config : PROFILE_SERVICES_AND_FLAGS) {
            // 1 讀取默認(rèn)配置的開(kāi)啟狀態(tài)
            boolean supported = resources.getBoolean(config.mSupported);

            // 2 HearingAid 若不支持定硝,則繼續(xù)查詢(xún)特定的配置(兩者有一個(gè)開(kāi)啟,則開(kāi)啟)
            if (!supported && (config.mClass == HearingAidService.class) && isHearingAidSettingsEnabled(ctx)) {
                supported = true;
            }

            // 3 查詢(xún)優(yōu)先級(jí)更高的配置毫目,二者有一個(gè)開(kāi)啟蔬啡,則開(kāi)啟該 profile
            if (enabledProfiles != null && enabledProfiles.contains(config.mClass.getName())) {
                supported = true;
            }

            // 4 查詢(xún)更高優(yōu)先級(jí)的配置,若指定關(guān)閉镀虐,則應(yīng)該關(guān)閉箱蟆,否則添加到開(kāi)啟的列表
            if (supported && !isProfileDisabled(ctx, config.mMask)) {
                profiles.add(config.mClass);
            }
        }

        // 根據(jù)配置信息和既定規(guī)則,確定支持的 profile list
        sSupportedProfiles = profiles.toArray(new Class[profiles.size()]);
        // Gabledorsche 協(xié)議棧有關(guān)配置粉私,由下面的配置文件可知顽腾,此處是開(kāi)啟的
        sIsGdEnabledUptoScanningLayer = resources.getBoolean(R.bool.enable_gd_up_to_scanning_layer);
    }
}
2.2.1 Default Config
public class Config {

    private static class ProfileConfig {
        Class mClass;
        int mSupported;
        long mMask;

        ProfileConfig(Class theClass, int supportedFlag, long mask) {
            mClass = theClass;
            mSupported = supportedFlag;
            mMask = mask;
        }
    }

    private static final ProfileConfig[] PROFILE_SERVICES_AND_FLAGS = {
            new ProfileConfig(HeadsetService.class, R.bool.profile_supported_hs_hfp,
                    (1 << BluetoothProfile.HEADSET)),
            new ProfileConfig(A2dpService.class, R.bool.profile_supported_a2dp,
                    (1 << BluetoothProfile.A2DP)),
            new ProfileConfig(A2dpSinkService.class, R.bool.profile_supported_a2dp_sink,
                    (1 << BluetoothProfile.A2DP_SINK)),
            new ProfileConfig(HidHostService.class, R.bool.profile_supported_hid_host,
                    (1 << BluetoothProfile.HID_HOST)),
            new ProfileConfig(PanService.class, R.bool.profile_supported_pan,
                    (1 << BluetoothProfile.PAN)),
            new ProfileConfig(GattService.class, R.bool.profile_supported_gatt,
                    (1 << BluetoothProfile.GATT)),
            new ProfileConfig(BluetoothMapService.class, R.bool.profile_supported_map,
                    (1 << BluetoothProfile.MAP)),
            new ProfileConfig(HeadsetClientService.class, R.bool.profile_supported_hfpclient,
                    (1 << BluetoothProfile.HEADSET_CLIENT)),
            new ProfileConfig(AvrcpTargetService.class, R.bool.profile_supported_avrcp_target,
                    (1 << BluetoothProfile.AVRCP)),
            new ProfileConfig(AvrcpControllerService.class,
                    R.bool.profile_supported_avrcp_controller,
                    (1 << BluetoothProfile.AVRCP_CONTROLLER)),
            new ProfileConfig(SapService.class, R.bool.profile_supported_sap,
                    (1 << BluetoothProfile.SAP)),
            new ProfileConfig(PbapClientService.class, R.bool.profile_supported_pbapclient,
                    (1 << BluetoothProfile.PBAP_CLIENT)),
            new ProfileConfig(MapClientService.class, R.bool.profile_supported_mapmce,
                    (1 << BluetoothProfile.MAP_CLIENT)),
            new ProfileConfig(HidDeviceService.class, R.bool.profile_supported_hid_device,
                    (1 << BluetoothProfile.HID_DEVICE)),
            new ProfileConfig(BluetoothOppService.class, R.bool.profile_supported_opp,
                    (1 << BluetoothProfile.OPP)),
            new ProfileConfig(BluetoothPbapService.class, R.bool.profile_supported_pbap,
                    (1 << BluetoothProfile.PBAP)),
            new ProfileConfig(LeAudioService.class, R.bool.profile_supported_le_audio,
                    (1 << BluetoothProfile.LE_AUDIO)),
            new ProfileConfig(VolumeControlService.class, R.bool.profile_supported_vc,
                    (1 << BluetoothProfile.VOLUME_CONTROL)),
            new ProfileConfig(McpService.class, R.bool.profile_supported_mcp_server,
                    (1 << BluetoothProfile.MCP_SERVER)),
            new ProfileConfig(HearingAidService.class,
                    com.android.internal.R.bool.config_hearing_aid_profile_supported,
                    (1 << BluetoothProfile.HEARING_AID)),
            new ProfileConfig(CsipSetCoordinatorService.class,
                    R.bool.profile_supported_csip_set_coordinator,
                    (1 << BluetoothProfile.CSIP_SET_COORDINATOR)),
    };
}

以上 Profile 的開(kāi)關(guān)配置如下:
packages/apps/Bluetooth/res/values/config.xml

    <bool name="profile_supported_a2dp">true</bool>
    <bool name="profile_supported_a2dp_sink">false</bool>             // false
    <bool name="profile_supported_hs_hfp">true</bool>
    <bool name="profile_supported_hfpclient">false</bool>             // false
    <bool name="profile_supported_hfp_incallservice">true</bool>
    <bool name="profile_supported_hid_host">true</bool>
    <bool name="profile_supported_opp">true</bool>
    <bool name="profile_supported_pan">true</bool>
    <bool name="profile_supported_pbap">true</bool>
    <bool name="profile_supported_gatt">true</bool>
    <bool name="pbap_include_photos_in_vcard">true</bool>
    <bool name="pbap_use_profile_for_owner_vcard">true</bool>
    <bool name="profile_supported_map">true</bool>
    <bool name="profile_supported_avrcp_target">true</bool>
    <bool name="profile_supported_avrcp_controller">false</bool>      // false
    <bool name="profile_supported_sap">false</bool>                   // false
    <bool name="profile_supported_pbapclient">false</bool>            // false
    <bool name="profile_supported_mapmce">false</bool>                // false
    <bool name="profile_supported_hid_device">true</bool>
    <bool name="profile_supported_le_audio">true</bool>
    <bool name="profile_supported_vc">true</bool>
    <bool name="profile_supported_mcp_server">true</bool>
    <bool name="profile_supported_csip_set_coordinator">true</bool>

    <bool name="enable_gd_up_to_scanning_layer">true</bool>
2.2.2 HearingAid
    private static boolean isHearingAidSettingsEnabled(Context context) {
        final String flagOverridePrefix = "sys.fflag.override.";
        final String hearingAidSettings = "settings_bluetooth_hearing_aid";

        // Override precedence:
        // Settings.Global -> sys.fflag.override.* -> static list

        // Step 1: check if hearing aid flag is set in Settings.Global.
        String value;
        if (context != null) {
            value = Settings.Global.getString(context.getContentResolver(), hearingAidSettings);
            if (!TextUtils.isEmpty(value)) {
                return Boolean.parseBoolean(value);
            }
        }

        // Step 2: check if hearing aid flag has any override.
        value = SystemProperties.get(flagOverridePrefix + hearingAidSettings);
        if (!TextUtils.isEmpty(value)) {
            return Boolean.parseBoolean(value);
        }

        // Step 3: return default value.
        return false;
    }
  1. 通過(guò) Settings 數(shù)據(jù)庫(kù)查詢(xún)配置
  2. 通過(guò) SystemProperties 查詢(xún)配置
2.2.3 System Config

從上文源代碼分析可知,這里只是獲取 System Config 對(duì) profile 的配置。
挖坑待填 // todo

    private static List<String> getSystemConfigEnabledProfilesForPackage(Context ctx) {
        SystemConfigManager systemConfigManager = ctx.getSystemService(SystemConfigManager.class);
        if (systemConfigManager == null) {
            return null;
        }
        return systemConfigManager.getEnabledComponentOverrides(ctx.getPackageName());
    }

frameworks/base/core/java/android/os/SystemConfigManager.java

    @SystemApi
    @NonNull
    public List<String> getEnabledComponentOverrides(@NonNull String packageName) {
        try {
            return mInterface.getEnabledComponentOverrides(packageName);
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }
2.2.4 Profile Disabled
    private static boolean isProfileDisabled(Context context, long profileMask) {
        final ContentResolver resolver = context.getContentResolver();
        final long disabledProfilesBitMask =
                Settings.Global.getLong(resolver, Settings.Global.BLUETOOTH_DISABLED_PROFILES, 0);

        return (disabledProfilesBitMask & profileMask) != 0;
    }

通過(guò) Settings 數(shù)據(jù)庫(kù)查詢(xún)特定字段配置

3. AdapterService 初始化

packages/apps/Bluetooth/src/com/android/bluetooth/btservice/AdapterService.java

  1. 首先抄肖,執(zhí)行靜態(tài)代碼塊久信,初始化 JNI;
  2. 其次漓摩,執(zhí)行 AdapterService 的 onCreate() 方法裙士;
  3. 最后,執(zhí)行 onBind() 方法管毙,返回 IBinder 子類(lèi)對(duì)象腿椎。

3.1 初始化 JNI

前文已經(jīng)加載了 libbluetooth_jni.so,這里開(kāi)始初始化 JNI夭咬。

public class AdapterService extends Service {

    static {
        classInitNative();
    }



    static native void classInitNative();
}

packages/apps/Bluetooth/jni/com_android_bluetooth_btservice_AdapterService.cpp

static void classInitNative(JNIEnv* env, jclass clazz) {
  jclass jniUidTrafficClass = env->FindClass("android/bluetooth/UidTraffic");
  android_bluetooth_UidTraffic.constructor =
      env->GetMethodID(jniUidTrafficClass, "<init>", "(IJJ)V");

  jclass jniCallbackClass =
      env->FindClass("com/android/bluetooth/btservice/JniCallbacks");
  sJniCallbacksField = env->GetFieldID(
      clazz, "mJniCallbacks", "Lcom/android/bluetooth/btservice/JniCallbacks;");

  method_oobDataReceivedCallback =
      env->GetMethodID(jniCallbackClass, "oobDataReceivedCallback",
                       "(ILandroid/bluetooth/OobData;)V");

  method_stateChangeCallback =
      env->GetMethodID(jniCallbackClass, "stateChangeCallback", "(I)V");

  method_adapterPropertyChangedCallback = env->GetMethodID(
      jniCallbackClass, "adapterPropertyChangedCallback", "([I[[B)V");
  method_discoveryStateChangeCallback = env->GetMethodID(
      jniCallbackClass, "discoveryStateChangeCallback", "(I)V");

  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[BIZ)V");
  method_sspRequestCallback =
      env->GetMethodID(jniCallbackClass, "sspRequestCallback", "([B[BIII)V");

  method_bondStateChangeCallback =
      env->GetMethodID(jniCallbackClass, "bondStateChangeCallback", "(I[BII)V");

  method_aclStateChangeCallback =
      env->GetMethodID(jniCallbackClass, "aclStateChangeCallback", "(I[BIII)V");

  method_linkQualityReportCallback = env->GetMethodID(
      jniCallbackClass, "linkQualityReportCallback", "(JIIIIII)V");

  method_setWakeAlarm = env->GetMethodID(clazz, "setWakeAlarm", "(JZ)Z");
  method_acquireWakeLock =
      env->GetMethodID(clazz, "acquireWakeLock", "(Ljava/lang/String;)Z");
  method_releaseWakeLock =
      env->GetMethodID(clazz, "releaseWakeLock", "(Ljava/lang/String;)Z");
  method_energyInfo = env->GetMethodID(
      clazz, "energyInfoCallback", "(IIJJJJ[Landroid/bluetooth/UidTraffic;)V");

  if (env->GetJavaVM(&vm) != JNI_OK) {
    ALOGE("Could not get JavaVM");
  }

  if (hal_util_load_bt_library((bt_interface_t const**)&sBluetoothInterface)) {
    ALOGE("No Bluetooth Library found");
  }
}
int hal_util_load_bt_library(const bt_interface_t** interface) {
  const char* sym = BLUETOOTH_INTERFACE_STRING;
  bt_interface_t* itf = nullptr;

  // The library name is not set by default, so the preset library name is used.
  void* handle = dlopen("libbluetooth.so", RTLD_NOW);
......

  // Get the address of the bt_interface_t.
  itf = (bt_interface_t*)dlsym(handle, sym);
......

  // Success.
  *interface = itf;
  return 0;
......
}

system/bt/include/hardware/bluetooth.h

#define BLUETOOTH_INTERFACE_STRING "bluetoothInterface"

注意: 該函數(shù)加載并打開(kāi)了 libbluetooth.so 庫(kù)文件啃炸,sBluetoothInterface 變量是 JNI 調(diào)用 libbluetooth.so 內(nèi)容的入口。

根據(jù) sym 可知卓舵,入口內(nèi)容如下:
system/bt/btif/src/bluetooth.cc

EXPORT_SYMBOL bt_interface_t bluetoothInterface = {
    sizeof(bluetoothInterface),
    init,
    enable,
    disable,
    cleanup,
    get_adapter_properties,
    get_adapter_property,
    set_adapter_property,
    get_remote_device_properties,
    get_remote_device_property,
    set_remote_device_property,
    nullptr,
    get_remote_services,
    start_discovery,
    cancel_discovery,
    create_bond,
    create_bond_out_of_band,
    remove_bond,
    cancel_bond,
    get_connection_state,
    pin_reply,
    ssp_reply,
    get_profile_interface,               // 通過(guò)它可以獲取其他profile的入口
    dut_mode_configure,
    dut_mode_send,
    le_test_mode,
    set_os_callouts,
    read_energy_info,
    dump,
    dumpMetrics,
    config_clear,
    interop_database_clear,
    interop_database_add,
    get_avrcp_service,
    obfuscate_address,
    get_metric_id,
    set_dynamic_audio_buffer_size,
    generate_local_oob_data
};

各種 profile 可以通過(guò) get_profile_interface() 函數(shù)南用,獲取到 profile 的入口。
該函數(shù)可以使用的有效ID如下:
system/bt/include/hardware/bluetooth.h

/** Bluetooth profile interface IDs */
#define BT_PROFILE_HANDSFREE_ID "handsfree"
#define BT_PROFILE_HANDSFREE_CLIENT_ID "handsfree_client"
#define BT_PROFILE_ADVANCED_AUDIO_ID "a2dp"
#define BT_PROFILE_ADVANCED_AUDIO_SINK_ID "a2dp_sink"
#define BT_PROFILE_SOCKETS_ID "socket"
#define BT_PROFILE_HIDHOST_ID "hidhost"
#define BT_PROFILE_HIDDEV_ID "hiddev"
#define BT_PROFILE_PAN_ID "pan"
#define BT_PROFILE_MAP_CLIENT_ID "map_client"
#define BT_PROFILE_SDP_CLIENT_ID "sdp"
#define BT_PROFILE_GATT_ID "gatt"
#define BT_PROFILE_AV_RC_ID "avrcp"
#define BT_PROFILE_AV_RC_CTRL_ID "avrcp_ctrl"
#define BT_PROFILE_HEARING_AID_ID "hearing_aid"
#define BT_KEYSTORE_ID "bluetooth_keystore"

3.2 AdapterService 初始化

packages/apps/Bluetooth/src/com/android/bluetooth/btservice/AdapterService.java

public class AdapterService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        // 1 負(fù)責(zé)解析藍(lán)牙設(shè)備的掃描結(jié)果
        mRemoteDevices = new RemoteDevices(this, Looper.getMainLooper());
        mRemoteDevices.init();

        // 清理調(diào)用 discovery() 的方法的包名的集合
        clearDiscoveringPackages();

        mBinder = new AdapterServiceBinder(this);
        mAdapterProperties = new AdapterProperties(this);
        mAdapterStateMachine = AdapterState.make(this);
        mJniCallbacks = new JniCallbacks(this, mAdapterProperties);

        // 2
        mBluetoothKeystoreService = new BluetoothKeystoreService(isCommonCriteriaMode());
        mBluetoothKeystoreService.start();
        int configCompareResult = mBluetoothKeystoreService.getCompareResult();

        // Android TV doesn't show consent dialogs for just works and encryption only le pairing
        boolean isAtvDevice = getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_LEANBACK_ONLY);
        // 3
        initNative(isGuest(), isNiapMode(), configCompareResult, isAtvDevice);
        mNativeAvailable = true;
        mCallbacks = new RemoteCallbackList<IBluetoothCallback>();

        // 4
        getAdapterPropertyNative(AbstractionLayer.BT_PROPERTY_BDADDR);
        getAdapterPropertyNative(AbstractionLayer.BT_PROPERTY_BDNAME);
        getAdapterPropertyNative(AbstractionLayer.BT_PROPERTY_CLASS_OF_DEVICE);

        mAlarmManager = getSystemService(AlarmManager.class);
        mPowerManager = getSystemService(PowerManager.class);
        mBatteryStatsManager = getSystemService(BatteryStatsManager.class);

        // 2.1 為何不跟前面放在一起執(zhí)行
        mBluetoothKeystoreService.initJni();

        // 5
        mSdpManager = SdpManager.init(this);

        registerReceiver(mAlarmBroadcastReceiver, new IntentFilter(ACTION_ALARM_WAKEUP));

        // 6
        mDatabaseManager = new DatabaseManager(this);
        mDatabaseManager.start(MetadataDatabase.createDatabase(this));

        // Phone policy is specific to phone implementations and hence if a device wants to exclude
        // it out then it can be disabled by using the flag below.
        if (getResources().getBoolean(com.android.bluetooth.R.bool.enable_phone_policy)) {
            Log.i(TAG, "Phone policy enabled");
            mPhonePolicy = new PhonePolicy(this, new ServiceFactory());
            mPhonePolicy.start();
        } else {
            Log.i(TAG, "Phone policy disabled");
        }

        // 7
        mActiveDeviceManager = new ActiveDeviceManager(this, new ServiceFactory());
        mActiveDeviceManager.start();

        // 8
        mSilenceDeviceManager = new SilenceDeviceManager(this, new ServiceFactory(),
                Looper.getMainLooper());
        mSilenceDeviceManager.start();

        // 9
        mBluetoothSocketManagerBinder = new BluetoothSocketManagerBinder(this);

        setAdapterService(this);

        // 10
        invalidateBluetoothCaches();

        // First call to getSharedPreferences will result in a file read into
        // memory cache. Call it here asynchronously to avoid potential ANR
        // in the future
        new AsyncTask<Void, Void, Void>() {
            // 11
            @Override
            protected Void doInBackground(Void... params) {
                getSharedPreferences(PHONEBOOK_ACCESS_PERMISSION_PREFERENCE_FILE,
                        Context.MODE_PRIVATE);
                getSharedPreferences(MESSAGE_ACCESS_PERMISSION_PREFERENCE_FILE,
                        Context.MODE_PRIVATE);
                getSharedPreferences(SIM_ACCESS_PERMISSION_PREFERENCE_FILE, Context.MODE_PRIVATE);
                return null;
            }
        }.execute();

        // 12
        try {
            int systemUiUid = getApplicationContext()
                    .createContextAsUser(UserHandle.SYSTEM, /* flags= */ 0)
                    .getPackageManager()
                    .getPackageUid("com.android.systemui", PackageManager.MATCH_SYSTEM_ONLY);

            Utils.setSystemUiUid(systemUiUid);
        } catch (PackageManager.NameNotFoundException e) {
            // Some platforms, such as wearables do not have a system ui.
            Log.w(TAG, "Unable to resolve SystemUI's UID.", e);
        }

        // 13
        IntentFilter filter = new IntentFilter(Intent.ACTION_USER_SWITCHED);
        getApplicationContext().registerReceiverForAllUsers(sUserSwitchedReceiver, filter, null, null);
        int fuid = ActivityManager.getCurrentUser();
        Utils.setForegroundUserId(fuid);
    }
}
3.2.1 Remote Device 初始化

packages/apps/Bluetooth/src/com/android/bluetooth/btservice/RemoteDevices.java

final class RemoteDevices {

    RemoteDevices(AdapterService service, Looper looper) {
        sAdapter = BluetoothAdapter.getDefaultAdapter();
        sAdapterService = service;
        sSdpTracker = new ArrayList<BluetoothDevice>();
        mDevices = new HashMap<String, DeviceProperties>();
        mDeviceQueue = new LinkedList<String>();
        mHandler = new RemoteDevicesHandler(looper);
    }



    void init() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothHeadset.ACTION_HF_INDICATORS_VALUE_CHANGED);
        filter.addAction(BluetoothHeadset.ACTION_VENDOR_SPECIFIC_HEADSET_EVENT);
        filter.addCategory(BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_COMPANY_ID_CATEGORY + "."
                + BluetoothAssignedNumbers.PLANTRONICS);
        filter.addCategory(BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_COMPANY_ID_CATEGORY + "."
                + BluetoothAssignedNumbers.APPLE);
        filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        sAdapterService.registerReceiver(mReceiver, filter);
    }


    class DeviceProperties {
        private String mName;
        private byte[] mAddress;
        private int mBluetoothClass = BluetoothClass.Device.Major.UNCATEGORIZED;
        private short mRssi;
        private String mAlias;
        private BluetoothDevice mDevice;
        private boolean mIsBondingInitiatedLocally;
        private int mBatteryLevel = BluetoothDevice.BATTERY_LEVEL_UNKNOWN;
        @VisibleForTesting int mBondState;
        @VisibleForTesting int mDeviceType;
        @VisibleForTesting ParcelUuid[] mUuids;
......
    }
}

RemoteDevices 用于解析和存儲(chǔ)掃描發(fā)現(xiàn)的遠(yuǎn)程設(shè)備(對(duì)端設(shè)備)的信息

3.2.2 BluetoothKeystoreService 初始化

packages/apps/Bluetooth/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreService.java

public class BluetoothKeystoreService {

    public BluetoothKeystoreService(boolean isNiapMode) {
        mIsNiapMode = isNiapMode;
        mCompareResult = CONFIG_COMPARE_INIT;
        startThread();
    }


    public void start() {
        KeyStore keyStore = getKeyStore();

        mBluetoothKeystoreNativeInterface = Objects.requireNonNull(
                BluetoothKeystoreNativeInterface.getInstance(),
                "BluetoothKeystoreNativeInterface cannot be null when BluetoothKeystore starts");

        // Mark service as started
        setBluetoothKeystoreService(this);

        try {
            if (!keyStore.containsAlias(KEYALIAS) && mIsNiapMode) {
                mCompareResult = 0b11;
                return;
            }
        } catch (KeyStoreException e) {
            reportKeystoreException(e, "cannot find the keystore");
            return;
        }

        // Load decryption data from file.
        loadConfigData();
    }

BluetoothKeystoreService 用于存儲(chǔ)設(shè)備的密鑰信息(LinkKey掏湾、LTK)

3.2.3 初始化 Native ( Bluetooth Stack )

Bluetooth Initialization - Native Initialization

3.2.4 getAdapterPropertyNative

從 Stack 獲取藍(lán)牙適配器的屬性信息

3.2.5 SdpManager

packages/apps/Bluetooth/src/com/android/bluetooth/sdp/SdpManager.java

public class SdpManager {
    public static SdpManager init(AdapterService adapterService) {
        sSdpManager = new SdpManager(adapterService);
        return sSdpManager;
    }


    private SdpManager(AdapterService adapterService) {
        sSdpSearchTracker = new SdpSearchTracker();

        sAdapterService = adapterService;
        initializeNative();
        sNativeAvailable = true;
    }



    private native void initializeNative();
}

packages/apps/Bluetooth/jni/com_android_bluetooth_sdp.cpp

static void initializeNative(JNIEnv* env, jobject object) {
  const bt_interface_t* btInf = getBluetoothInterface();

  sBluetoothSdpInterface = (btsdp_interface_t*)btInf->get_profile_interface(
      BT_PROFILE_SDP_CLIENT_ID);
  sBluetoothSdpInterface->init(&sBluetoothSdpCallbacks);

  sCallbacksObj = env->NewGlobalRef(object);
}

初始化 SDP JNI裹虫,獲取 SDP 客戶端對(duì)象,用于 與 SDP 服務(wù)端相互操作融击。

3.2.6 DatabaseManager

packages/apps/Bluetooth/src/com/android/bluetooth/btservice/storage/DatabaseManager.java

public class DatabaseManager {

    public DatabaseManager(AdapterService service) {
        mAdapterService = service;
        mMetadataChangedLog = EvictingQueue.create(METADATA_CHANGED_LOG_MAX_SIZE);
    }


    public void start(MetadataDatabase database) {
        mDatabase = database;

        mHandlerThread = new HandlerThread("BluetoothDatabaseManager");
        mHandlerThread.start();
        mHandler = new DatabaseHandler(mHandlerThread.getLooper());

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        mAdapterService.registerReceiver(mReceiver, filter);

        loadDatabase();
    }



    private void loadDatabase() {
        Message message = mHandler.obtainMessage(MSG_LOAD_DATABASE);
        mHandler.sendMessage(message);
......
    }


    class DatabaseHandler extends Handler {
        DatabaseHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATABASE: {
                    synchronized (mDatabase) {
                        List<Metadata> list;
                        try {
                            list = mDatabase.load();
                        } catch (IllegalStateException e) {
                            mDatabase = MetadataDatabase
                                    .createDatabaseWithoutMigration(mAdapterService);
                            list = mDatabase.load();
                        }
                        compactLastConnectionTime(list);
                        cacheMetadata(list);
                    }
                    break;
                }
                ......
            }
        }
    }
}

初始化數(shù)據(jù)庫(kù)筑公,隨后讀取數(shù)據(jù)庫(kù)的內(nèi)容,并轉(zhuǎn)成合適的格式緩存在內(nèi)存中尊浪。

3.2.7 ActiveDeviceManager

packages/apps/Bluetooth/src/com/android/bluetooth/btservice/ActiveDeviceManager.java

class ActiveDeviceManager {

    ActiveDeviceManager(AdapterService service, ServiceFactory factory) {
        mAdapterService = service;
        mFactory = factory;
        mAudioManager = (AudioManager) service.getSystemService(Context.AUDIO_SERVICE);
        mAudioManagerAudioDeviceCallback = new AudioManagerAudioDeviceCallback();
    }



    void start() {
        mHandlerThread = new HandlerThread("BluetoothActiveDeviceManager");
        mHandlerThread.start();
        mHandler = new ActiveDeviceManagerHandler(mHandlerThread.getLooper());

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
        filter.addAction(BluetoothA2dp.ACTION_ACTIVE_DEVICE_CHANGED);
        filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        filter.addAction(BluetoothHeadset.ACTION_ACTIVE_DEVICE_CHANGED);
        filter.addAction(BluetoothHearingAid.ACTION_ACTIVE_DEVICE_CHANGED);
        mAdapterService.registerReceiver(mReceiver, filter);

        mAudioManager.registerAudioDeviceCallback(mAudioManagerAudioDeviceCallback, mHandler);
    }

初始化 ActiveDeviceManager 匣屡,啟動(dòng) Handler 線程、注冊(cè)廣播拇涤、向 AudioManager 注冊(cè)回調(diào)耸采。
該類(lèi)注釋了活躍設(shè)備的策略:


ActiveDevice Policy
3.2.8 SilenceDeviceManager

packages/apps/Bluetooth/src/com/android/bluetooth/btservice/SilenceDeviceManager.java

public class SilenceDeviceManager {
    SilenceDeviceManager(AdapterService service, ServiceFactory factory, Looper looper) {
        mAdapterService = service;
        mFactory = factory;
        mLooper = looper;
    }



    void start() {
        mHandler = new SilenceDeviceManagerHandler(mLooper);

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
        filter.addAction(BluetoothA2dp.ACTION_ACTIVE_DEVICE_CHANGED);
        filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        filter.addAction(BluetoothHeadset.ACTION_ACTIVE_DEVICE_CHANGED);
        mAdapterService.registerReceiver(mReceiver, filter);
    }
}

初始化 SilenceDeviceManager ,啟動(dòng) Handler 工育、注冊(cè)廣播。
該類(lèi)注釋了沉默設(shè)備的策略:


SilenceDevice Policy
3.2.9 BluetoothSocketManagerBinder

packages/apps/Bluetooth/src/com/android/bluetooth/btservice/BluetoothSocketManagerBinder.java

class BluetoothSocketManagerBinder extends IBluetoothSocketManager.Stub {
    BluetoothSocketManagerBinder(AdapterService service) {
        mService = service;
    }
}

創(chuàng)建 Socket profile 的 Binder 服務(wù)端對(duì)象搓彻,用于基于藍(lán)牙的 Socket 服務(wù)如绸。

3.2.10 invalidateBluetoothCaches

packages/apps/Bluetooth/src/com/android/bluetooth/btservice/AdapterService.java

    private void invalidateBluetoothCaches() {
        BluetoothAdapter.invalidateGetProfileConnectionStateCache();
        BluetoothAdapter.invalidateIsOffloadedFilteringSupportedCache();
        BluetoothDevice.invalidateBluetoothGetBondStateCache();
        BluetoothAdapter.invalidateBluetoothGetStateCache();
    }

以上四個(gè)方法調(diào)用,全部都是調(diào)用同一個(gè)方法 PropertyInvalidatedCache.invalidateCache()旭贬,僅僅參數(shù)不同而已怔接,下面以第一個(gè)為例介紹。
frameworks/base/core/java/android/bluetooth/BluetoothAdapter.java

    /** @hide */
    public static void invalidateGetProfileConnectionStateCache() {
        PropertyInvalidatedCache.invalidateCache(BLUETOOTH_PROFILE_CACHE_PROPERTY);
    }

frameworks/base/core/java/android/app/PropertyInvalidatedCache.java

    public static void invalidateCache(@NonNull String name) {

        synchronized (sCorkLock) {
            Integer numberCorks = sCorks.get(name);
            if (numberCorks != null && numberCorks > 0) {
                return;
            }
            invalidateCacheLocked(name);
        }
    }

符合要求則更新緩存稀轨,該緩存為所有的process共享扼脐。

3.2.11 getSharedPreferences

異步初始化,避免 ANR。

3.2.12 setSystemUiUid

packages/apps/Bluetooth/src/com/android/bluetooth/Utils.java

    static int sSystemUiUid = UserHandle.USER_NULL;
    public static void setSystemUiUid(int uid) {
        Utils.sSystemUiUid = uid;
    }

緩存 com.android.systemui 進(jìn)程的 UID瓦侮,可用于后續(xù)判斷調(diào)用者是否來(lái)自該進(jìn)程艰赞。

3.2.13 Set Foreground User

packages/apps/Bluetooth/src/com/android/bluetooth/Utils.java

    static int sForegroundUserId = UserHandle.USER_NULL;
    public static void setForegroundUserId(int uid) {
        Utils.sForegroundUserId = uid;
    }


    public static final BroadcastReceiver sUserSwitchedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
                int fuid = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
                Utils.setForegroundUserId(fuid);
            }
        }
    };

緩存當(dāng)前 User 的 UID,可用于后續(xù)判斷調(diào)用者是否來(lái)自該進(jìn)程肚吏。
注冊(cè)了用戶變化的廣播方妖,用戶變化時(shí),更新緩存罚攀。

3.3 返回 IBinder 對(duì)象

public class AdapterService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }



    @Override
    public void onCreate() {
......
        mBinder = new AdapterServiceBinder(this);
......
    }
}

返回的對(duì)象是 AdapterServiceBinder 党觅,是 IBluetooth.Stub 的子類(lèi),對(duì)端進(jìn)程拿到的是其代理對(duì)象斋泄,用于跨進(jìn)程通信杯瞻。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市炫掐,隨后出現(xiàn)的幾起案子魁莉,更是在濱河造成了極大的恐慌,老刑警劉巖卒废,帶你破解...
    沈念sama閱讀 216,997評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件沛厨,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡摔认,警方通過(guò)查閱死者的電腦和手機(jī)逆皮,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)参袱,“玉大人电谣,你說(shuō)我怎么就攤上這事∧ㄊ矗” “怎么了剿牺?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,359評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)环壤。 經(jīng)常有香客問(wèn)我晒来,道長(zhǎng),這世上最難降的妖魔是什么郑现? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,309評(píng)論 1 292
  • 正文 為了忘掉前任湃崩,我火速辦了婚禮,結(jié)果婚禮上接箫,老公的妹妹穿的比我還像新娘攒读。我一直安慰自己,他們只是感情好辛友,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評(píng)論 6 390
  • 文/花漫 我一把揭開(kāi)白布薄扁。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪邓梅。 梳的紋絲不亂的頭發(fā)上脱盲,一...
    開(kāi)封第一講書(shū)人閱讀 51,258評(píng)論 1 300
  • 那天,我揣著相機(jī)與錄音震放,去河邊找鬼宾毒。 笑死,一個(gè)胖子當(dāng)著我的面吹牛殿遂,可吹牛的內(nèi)容都是我干的诈铛。 我是一名探鬼主播,決...
    沈念sama閱讀 40,122評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼墨礁,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼幢竹!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起恩静,我...
    開(kāi)封第一講書(shū)人閱讀 38,970評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤焕毫,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后驶乾,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體邑飒,經(jīng)...
    沈念sama閱讀 45,403評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評(píng)論 3 334
  • 正文 我和宋清朗相戀三年级乐,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了疙咸。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,769評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡风科,死狀恐怖撒轮,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情贼穆,我是刑警寧澤题山,帶...
    沈念sama閱讀 35,464評(píng)論 5 344
  • 正文 年R本政府宣布,位于F島的核電站故痊,受9級(jí)特大地震影響顶瞳,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜愕秫,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評(píng)論 3 327
  • 文/蒙蒙 一浊仆、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧豫领,春花似錦、人聲如沸舔琅。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,705評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至课蔬,卻和暖如春囱稽,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背二跋。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,848評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工战惊, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人扎即。 一個(gè)月前我還...
    沈念sama閱讀 47,831評(píng)論 2 370
  • 正文 我出身青樓吞获,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親谚鄙。 傳聞我的和親對(duì)象是個(gè)殘疾皇子各拷,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容