EyeQ Tech
EyeQ Tech

Reputation: 7358

Android, track when app goes to background

Background: I dump some data in the Application class, and save it to files after a short interval or when the app goes to background (say, when the user presses the Home button or the Task-switcher button). I don't want to use onPause() of Activity class because there are many activities in the app, I have to check onPause() for all of them. And onPause is also called when I jump from one activity to another in my app (which creates unnecessary saving action).

Question: Is there a universal event fired when the app going to background, regardless of which activity it is at?

Thanks

Upvotes: 0

Views: 635

Answers (2)

Eric Tobias
Eric Tobias

Reputation: 3266

onStop() is called when activities are hidden from view, i.e. the user pressed the home button. onPause() is only used when an Activity is hidden, that is, partially visible due to some overlap. Of course, onPause() is called right before onStop() is called. You can see all of the lifecycle over at Android Developers. I would encourage you to work with the lifecycle and not against it. Save your data when the state changes.

For scheduled data storage, I would suggest you use a timer. As you commit all the data to the application context, and you can live with fewer recovery points, I would suggest storing the date in the onDestroy() call. If not, I suggest implementing a TimerTask to schedule regular serialisations of your data.

To answer your question, no! It simply is not Android to consider your application in total and have one lifecycle. You have one lifecycle per activity and all activities are tied together by a stack and their respective lifecycles.

Upvotes: 0

user543
user543

Reputation: 3633

Check the below code continuously means u can use Timer class.

ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<RunningTaskInfo> runningTasks = null;
try {
    runningTasks = activityManager.getRunningTasks(1);
} catch (Exception e) {

}
RunningTaskInfo runningTaskInfo = runningTasks.get(0);
ComponentName topActivity = runningTaskInfo.topActivity;
if(topActivity.getPackageName().equals(your packagename)){
   S.o.p("fine");}
else{
   S.o.p.("application sent to background");}

Upvotes: 1

Related Questions