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
\$\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\$
  • \$\begingroup\$ But on stop method is for the activity, not the application... \$\endgroup\$ – Ruchir Baronia Dec 19 '15 at 12:40
  • \$\begingroup\$ Are you using an IntentService ? \$\endgroup\$ – elenfoiro78 Dec 19 '15 at 12:52
  • \$\begingroup\$ Yes, I am using a service. \$\endgroup\$ – Ruchir Baronia Dec 19 '15 at 19:04
  • \$\begingroup\$ OK, edited my answer \$\endgroup\$ – elenfoiro78 Dec 19 '15 at 19:43
  • \$\begingroup\$ I don't understand what is going on in the for loop. Can you explain? \$\endgroup\$ – Ruchir Baronia Dec 20 '15 at 3:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.