Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App closing event in Android

Is there any way to know your application is running ? I want to run a piece of code when Android app is just closed. Any suggestion will be appreciated.

like image 746
mani Avatar asked May 08 '14 06:05

mani


2 Answers

Just to answer my own question now after so much time. When user close the app, the process is terminated with no notice. onDestroy is not guaranteed to be called. only when you explicitly call finish().

like image 167
mani Avatar answered Sep 29 '22 23:09

mani


I suggest you to make a custom application class and note store the visibility of application wether it is running in background or not.obviously if you don't close the application like this

How to close Android application?

have a look at this so that you don't close it from background and perform the visibility check like this.

public class MyApplication extends Application {

public static boolean isActivityVisible() {
return activityVisible;
}  

public static void activityResumed() {
activityVisible = true;
}

public static void activityPaused() {
activityVisible = false;
}

 private static boolean activityVisible;
}

and this is how you register you application class to the manifest file.

<application
android:name="your.app.package.MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name" >

and override these two methods like this.

@Override
protected void onResume() {
super.onResume();
MyApplication.activityResumed();
}

@Override
protected void onPause() {
super.onPause();
MyApplication.activityPaused();
}

now check this status and perform what you like if it is running in background.You can take help of Booleans to check if the application is not closed by other reasons.

like image 44
Dharma Avatar answered Sep 29 '22 23:09

Dharma