I need to get the app from background into foreground. I managed to make this work for versions below 31 by using this code:
public static void bringApplicationToFront(Context context)
{
Log.d("bringApplicationToFront");
Intent notificationIntent = new Intent(context, SplashActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
pendingIntent = PendingIntent.getActivity
(context, 0, notificationIntent, PendingIntent.FLAG_MUTABLE);
}
else {
pendingIntent = PendingIntent.getActivity
(context, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
}
try
{
pendingIntent.send();
}
catch (PendingIntent.CanceledException e)
{
e.printStackTrace();
}
}
SplashActivity is my root Activity. I tried this with a BroadcastReceiver and also by using background thread which runs the code with a delay.
I call this method from Application class like this:
@Override
public void onTrimMemory(int level)
{
super.onTrimMemory(level);
if (level == TRIM_MEMORY_UI_HIDDEN) {
Print.e("App is background");
bringApplicationToFront();
}
}
How can I make this work for API 31?
Android has tightened up the restriction around launching an
Activityfrom a background process (Service,BroadcastReceiver, etc.). You can read about this here: https://developer.android.com/guide/components/activities/background-starts#exceptionsProbably the only thing you can do is request
SYSTEM_ALERT_WINDOWpermission as a workaround. Personally I think this is a terrible hack and Android will probably close this loophole in a future version.