How to detect whether the phone connected to android auto

≯℡__Kan透↙ 提交于 2019-12-05 22:13:45

You can check UIMode like in google example:

https://github.com/googlesamples/android-UniversalMusicPlayer/blob/master/mobile/src/main/java/com/example/android/uamp/utils/CarHelper.java#L106

public static boolean isCarUiMode(Context c) {
    UiModeManager uiModeManager = (UiModeManager) c.getSystemService(Context.UI_MODE_SERVICE);
    if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_CAR) {
        LogHelper.d(TAG, "Running in Car mode");
        return true;
    } else {
        LogHelper.d(TAG, "Running on a non-Car mode");
        return false;
    }
}

Then before run alarm check isCarUiMode result

As you mentioned you can register a reciever for "com.google.android.gms.car.media.STATUS" and save the status into e.g. shared preferences.

When the application wants to display the alarm, it can check the saved status. If status is connected do not show the alram, otherwise show it.

Something like:

public void onReceive(Context context, Intent intent) {
     String status = intent.getStringExtra("media_connection_status");
     boolean isConnectedToCar = "media_connected".equals(status);
     SharedPreferences sharedPrefs = context.getSharedPreferences(
            "myprefs", Context.MODE_PRIVATE);
     SharedPreferences.Editor editor = sharedPrefs.edit();
     editor.putBoolean("isConnected", isConnectedToCar);
     editor.commit();
}

And when the alarm is triggered:

SharedPreferences sharedPrefs = context.getSharedPreferences(
            "myprefs", Context.MODE_PRIVATE);
boolean isConnected = sharedPref.getBoolean("isConnected", false);
if (!isConnected) {
   // Alarm
}

Hope that helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!