简体   繁体   English

Android,跟踪应用何时进入后台

[英]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). 背景:我将一些数据转储到Application类中,并在短暂的间隔后或应用程序进入后台(例如,当用户按下“主页”按钮或“任务切换器”按钮时)将其保存到文件中。 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. 我不想使用Activity类的onPause(),因为应用程序中有许多活动,我必须检查所有活动的onPause()。 And onPause is also called when I jump from one activity to another in my app (which creates unnecessary saving action). 当我从应用程序中的一项活动跳到另一项活动时(会创建不必要的保存操作),也会调用onPause。

Question : Is there a universal event fired when the app going to background, regardless of which activity it is at? 问题 :当应用程序进入后台时,无论它处于哪个活动,都会触发一个通用事件吗?

Thanks 谢谢

Check the below code continuously means u can use Timer class. 连续检查以下代码意味着您可以使用Timer类。

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");}

onStop() is called when activities are hidden from view, ie the user pressed the home button. 当活动从视图中隐藏时(即用户按下主页按钮onStop()将调用onStop() onPause() is only used when an Activity is hidden, that is, partially visible due to some overlap. onPause()仅在Activity被隐藏时使用,即由于某些重叠而部分可见。 Of course, onPause() is called right before onStop() is called. 当然, onPause()onStop()被调用之前被调用。 You can see all of the lifecycle over at Android Developers . 您可以在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. 当您将所有数据提交到应用程序上下文中时,您可以使用较少的恢复点,因此建议将日期存储在onDestroy()调用中。 If not, I suggest implementing a TimerTask to schedule regular serialisations of your data. 如果没有,我建议实现一个TimerTask来安排数据的常规序列化。

To answer your question, no! 要回答您的问题,不! It simply is not Android to consider your application in total and have one lifecycle. 根本不是Android要整体考虑您的应用程序并拥有一个生命周期。 You have one lifecycle per activity and all activities are tied together by a stack and their respective lifecycles. 每个活动有一个生命周期,所有活动都由堆栈及其各自的生命周期捆绑在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM