问题
I'm developing an audio player application, and I need to determine when the user's device is connected to Android Auto.
The application features an alarm, and I want to make sure it doesn't go off while the user is driving.
To determine whether my music-service (MediaBrowserService
) works, I can use some flags in onCreate and onDestroy, or register reciver for "com.google.android.gms.car.media.STATUS" action - but it's a bad idea because alarm clock can trigger in any time. And not only when my music-service is running.
For alarm and I use AlarmManager
and pending intent.
Maybe someone faced with similar problems?
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/36293866/how-to-detect-whether-the-phone-connected-to-android-auto