5

I searched, but could not get any answer Is there any broadcast do detect when our phone is connected to Android Auto?

I have this code but that need to be run by some event.

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;
}
Parth
  • 1,908
  • 1
  • 19
  • 37

1 Answers1

8

Looking into the documentation on the UiModeManager, I found ACTION_ENTER_CAR_MODE, as well as ACTION_EXIT_CAR_MODE.

Using these, you can create and register a receiver in the manifest like so:

<receiver
  android:name=".CarModeReceiver"
  android:enabled="true"
  android:exported="true">
  <intent-filter>
    <action android:name="android.app.action.ENTER_CAR_MODE"/>
    <action android:name="android.app.action.EXIT_CAR_MODE"/>
  </intent-filter>
</receiver>

Then in the implementation of the receiver, you can do something like this

public class CarModeReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(action)) {
        Log.d("CarModeReceiver", "Car Mode");
      } else if (UiModeManager.ACTION_EXIT_CAR_MODE.equals(action)) {
        Log.d("CarModeReceiver", "Non-Car Mode");
      }
  }
}
salminnella
  • 744
  • 2
  • 6
  • 17
  • Those implicit broadcasts won't work if you target API level 26 or above, because ACTION_ENTER_CAR_MODE and ACTION_EXIT_CAR_MODE are not exempted from the background execution limits. See https://developer.android.com/guide/components/broadcast-exceptions – Headcracker Mar 18 '20 at 13:40