3
\$\begingroup\$

Background:

I have a background service with a timer. It opens up a new activity when 20 seconds are over.

Currently, my app is using componentCallbacks2 to detect when the user has pressed the home screen, or has left the app, and on detection, I stop the timer, so that the activity doesn't get called.

But, for some reason, componentCallBacks2 does not get called when the user just closes out of the app:

enter image description here

Here you can see the user closing an app. For some reason, my app doesn't stop its processes when the app is closed. And, the timer continues to run. This results in the activity popping up on the users screen after 20 seconds, even though the user isn't in the app.

How can I detect if the app has been closed so that I can stop the timer? I have read on this topic in many other sources, and those sources just say to use the onStop method. I can't do that, because the onStop gets called whenever there is a change in activities

So, where should I stop the timer?


Image source.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

From Android documentation:

An operation running on an IntentService can't be interrupted

Anyway, there is still a solution based on preventing the launch if your app is closed:

1/ In your app

Pass your application pid in the "extra" part of the Intent used to launch the background task.

To get you app pid :

android.os.Process.myPid();

2/ In the background task process

When your task is finished (the 20 seconds have passed), check if the app is still runnning before launching the Activity

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> pids = am.getRunningAppProcesses();

for (int i = 0; i < pids.size(); ++i)
    if (pid == pids.get(i).pid) {
        // Launch your activity because your app is still runnning
    }

assuming that the variable "pid" is the pid that came in the intent extra data.

\$\endgroup\$
6
  • \$\begingroup\$ But on stop method is for the activity, not the application... \$\endgroup\$ Commented Dec 19, 2015 at 12:40
  • \$\begingroup\$ Are you using an IntentService ? \$\endgroup\$ Commented Dec 19, 2015 at 12:52
  • \$\begingroup\$ Yes, I am using a service. \$\endgroup\$ Commented Dec 19, 2015 at 19:04
  • \$\begingroup\$ OK, edited my answer \$\endgroup\$ Commented Dec 19, 2015 at 19:43
  • \$\begingroup\$ I don't understand what is going on in the for loop. Can you explain? \$\endgroup\$ Commented Dec 20, 2015 at 3:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .