Gaurav Agarwal
Gaurav Agarwal

Reputation: 19102

How to know when the user has closed the Android application?

Is there any way of finding when an application is closed (either by user or system) i.e the application can only be restarted by the user by pressing the application launcher icon.

I think it is only possible if Android system broadcast any Intent when a name of a process is removed from getRunningAppProcesses().

I have read all the possible Q&A on the SO and the question is not related with the ActivityLifecycle.

Upvotes: 1

Views: 219

Answers (2)

Akos Cz
Akos Cz

Reputation: 12790

Hmm.. You can manually monitor /proc on the filesystem to see if the process id is present for the application you care about.

From your terminal window try the following. For example :

> MYPID=(`adb shell ps | grep com.mydomain.myapp | awk '{print $2}'`)
> adb shell [ -d /proc/$MYPID ] && echo "PID $MYPID Exists"

Replace com.mydomain.myapp with your apps package name

There are several apps available to monitor processes on android. Take a look at http://code.google.com/p/android-os-monitor/

The android-os-monitor project uses a JNI layer to implement the interaction with /proc http://code.google.com/p/android-os-monitor/source/browse/OSMonitor/jni/process.c?repo=osmonitor

http://code.google.com/p/android-os-monitor/source/browse/OSMonitor/src/com/eolwral/osmonitor/JNIInterface.java?repo=osmonitor

http://code.google.com/p/android-os-monitor/source/browse/OSMonitor/src/com/eolwral/osmonitor/processes/ProcessList.java?repo=osmonitor

Upvotes: 2

Kristopher Micinski
Kristopher Micinski

Reputation: 7672

Generally, waiting for a user to "exit" an app is a bad idea, since:

  • The user never actually exists the app, they simply leave it on the activity stack and come back to it later.
  • A user might do anything during your database update, such as reenter the app.
  • You can't really detect this without very hacky solutions; this is by design of the API, because you shouldn't need to do these kinds of things.

Because of this, I think any solution based on waiting for the app to "die" is a bad one. Instead, you should come up with a solution that respects the semantics of the application. For example, if you are entering data in one of its content providers then it should handle consistency (across fragments in the app, for example).

Upvotes: 4

Related Questions