1

In my app, I have a Service running in the background (and foreground).

In this Service, there's a CountdownTimer and when it finishes I want to launch the app in a certain Activity and do some stuff in the Activity automatically, and I want this to work even if my app is killed or closed.

I've seen some answers, this is one of them, but it won't work for me. I've found a better solution and posted it as an answer below, but still, it works only if the app is closed but not completely killed.

How can I launch an Activity from a background Service even when the app is closed or killed?

Elias Prado
  • 1,518
  • 2
  • 17
  • 32
Nitzan Daloomy
  • 166
  • 5
  • 24

4 Answers4

0

You need to start service in FOREGROUND_SERVICE Like this

  Intent intent = new Intent(this, AppService.class);
        
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(intent);
    }

And Add This line in Main.xml

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
0

As NitzanDaloomy suggested in his answer here we can use SYSTEM_ALERT_WINDOW but that won't open the app when it is killed but bring it in the recents list. Now, because our app is no longer closed(it is in background), we can use startActivity(Intent intent) and then, the app will open

Sambhav Khandelwal
  • 3,585
  • 2
  • 7
  • 38
0

You need to request and enable overlay permission for your app to achieve that. Without that, your app cannot lunch any activity on the screen when it is in the foreground.

I had the same issue and was able to resolve it after seeing the response from this answer

Peter Akwa
  • 77
  • 1
  • 6
-1

See this answer.
This answer suggests enabling ScreeanOverlay settings because as of Android 10 and later you can no longer open an activity from the background just by calling the lines I've used.
To make it work, you'd have to add this permission through your Manifest.xml:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

And then the user would have to enable the Display over other apps setting.
I searched for an option to get the user to this setting more easily and found this answer.
This answer gives a code that redirects the user to the Display over other apps setting

if (!Settings.canDrawOverlays(this)) {
    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
    startActivityForResult(intent, 0);
}

and then I guide the user with the notification's content (text) on how to enable the setting.
Once the setting is enabled, The lines I've used before work.\

So, problem solved?

Not Completely Solved

this whole configuration described above works, but only if the app is not killed.
If the app was killed and I try the method listed above, the app joins the recent apps list, but won't open and show up.

Nitzan Daloomy
  • 166
  • 5
  • 24