背景:每次啟動車子,手機都不會跟汽車藍牙自動鏈接。身為開車必聽歌的強迫癥患者,每次上車手動鏈接都很耗時,最近受李跳跳的啟發(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);
}