背景:每次啟動車子,手機(jī)都不會跟汽車藍(lán)牙自動鏈接。身為開車必聽歌的強(qiáng)迫癥患者,每次上車手動鏈接都很耗時(shí),最近受李跳跳的啟發(fā),感覺可以基于安卓的后臺保活機(jī)制,來自動鏈接藍(lán)牙以此解放雙手。
基本工作原理:
基于安卓的無障礙模式?;?、每十秒自動掃描周圍藍(lán)牙設(shè)備。當(dāng)發(fā)現(xiàn)汽車藍(lán)牙后,自動進(jìn)行鏈接。
注:得益于現(xiàn)在藍(lán)牙5.0的低功耗,所以長時(shí)間的藍(lán)牙掃描,并不會明顯影響手機(jī)續(xù)航能力
核心鏈接汽車藍(lán)牙代碼
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);
}