【車機藍牙寶】 藍牙鏈接部分的簡單分享

背景:每次啟動車子,手機都不會跟汽車藍牙自動鏈接。身為開車必聽歌的強迫癥患者,每次上車手動鏈接都很耗時,最近受李跳跳的啟發(fā),感覺可以基于安卓的后臺?;顧C制,來自動鏈接藍牙以此解放雙手。

基本工作原理:
基于安卓的無障礙模式保活、每十秒自動掃描周圍藍牙設備。當發(fā)現(xiàn)汽車藍牙后,自動進行鏈接。
注:得益于現(xiàn)在藍牙5.0的低功耗,所以長時間的藍牙掃描,并不會明顯影響手機續(xù)航能力

核心鏈接汽車藍牙代碼

public void connect(Context context, BluetoothDevice scanDevice) {
      if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
         return;
      }

      if (scanDevice.getBluetoothClass().getMajorDeviceClass() != BluetoothClass.Device.Major.AUDIO_VIDEO) {
         return;
      }
      mBluetoothAdapter.getProfileProxy(context, new BluetoothProfile.ServiceListener() {
         @Override
         public void onServiceConnected(int profile, BluetoothProfile proxy) {
            BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) proxy;
            Class btHeadsetCls = BluetoothHeadset.class;
            try {
               Method connect = btHeadsetCls.getMethod("connect", BluetoothDevice.class);
               connect.setAccessible(true);
               connect.invoke(bluetoothHeadset, scanDevice);
            } catch (Exception e) {
               Log.e(TAG, e + "");
            }
         }

         @Override
         public void onServiceDisconnected(int profile) {

         }
      }, BluetoothProfile.HEADSET);
   }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容