简体   繁体   English

Android:覆盖onPause和onResume - 正确的方法

[英]Android: overriding onPause and onResume - proper way

When overriding the onPause() and the onResume() methods of the activity, where is the proper location to call the super.onPause() and super.onResume() ? 覆盖活动的onPause()onResume()方法时,调用super.onPause()super.onResume()的正确位置在super.onPause() At the beginning of the method or at the end? 在方法开始时还是在结束时?

From http://developer.android.com/guide/components/activities.html#ImplementingLifecycleCallbacks : 来自http://developer.android.com/guide/components/activities.html#ImplementingLifecycleCallbacks

Your implementation of these lifecycle methods must always call the superclass implementation before doing any work, as shown in the examples above. 在执行任何工作之前,您对这些生命周期方法的实现必须始终调用超类实现,如上面的示例所示。

So, for lifecycle callbacks, like onPause() and onResume() , we should do super.onPause() or super.onResume() at the very beginning. 因此,对于生命周期回调,比如onPause()onResume() ,我们应该在一开始就做super.onPause()super.onResume() For other methods, it all depends on the semantics of the super class. 对于其他方法,这一切都取决于超类的语义。

Update: This is the accepted answer and it contains a nice amount of good information, including a useful diagram, pulled together into one place. 更新:这是接受的答案,它包含大量的好信息,包括一个有用的图表,汇集到一个地方。 However, it appears to be incorrect , at least according to the current Android documentation which, as the poster points out, is the ultimate source for information on the SDK. 然而,它似乎是不正确的 ,至少根据当前的Android文档,正如海报所指出的那样,它是SDK信息的最终来源。 Possibly the documentation was clarified after this answer was posted. 在发布此答案后,可能会澄清文档。 But, in any case, don't stop reading with this answer, check out espinchi's answer below . 但是,无论如何,请不要停止阅读这个答案,请查看下面的espinchi的答案 It has the documentation on its side. 它有自己的文档。


Placement of the super methods depends only on your preference. super方法的放置仅取决于您的偏好。 It would only matter if those methods were taking parameters OR if you were doing some concurrent work. 只要这些方法采用参数或者如果您正在进行一些并发工作,那将是唯一的问题。 For example if you do this: 例如,如果你这样做:

    @Override
    protected void onPause() {
        try {
            someOtherThread.join();
        } catch (InterruptedException e) {
            LOG.e(e);
        }
        super.onPause();
    }

it might block the thread and prevent super from being called. 它可能会阻塞线程并阻止super被调用。

I suggest that you should read all documentation available because they will help you much. 我建议您阅读所有可用的文档,因为它们会对您有所帮助。 For example this is what you can find in the onPause javadoc. 例如,您可以在onPause javadoc中找到它。 I bolded out the important parts: 我把重要的部分加粗了:

Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. 当活动进入后台但被(但)尚未被杀死时,被称为活动生命周期的一部分。 The counterpart to onResume(). onResume()的对应部分。

When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here. 当在活动A前面启动活动B时,将在A上调用此回调。在A的onPause()返回之前不会创建B,所以一定不要在这里做任何冗长的事情。

This callback is mostly used for saving any persistent state the activity is editing, to present a "edit in place" model to the user and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one. 回调主要用于保存活动正在编辑的任何持久状态,向用户显示“就地编辑”模型,并确保在没有先杀死此活动的情况下没有足够的资源来启动新活动时不会丢失任何内容。 This is also a good place to do things like stop animations and other things that consume a noticeable amount of CPU in order to make the switch to the next activity as fast as possible, or to close resources that are exclusive access such as the camera. 这也是一个很好的做法,例如停止动画和其他消耗大量CPU的事情,以便尽快切换到下一个活动,或者关闭独占访问的资源,如摄像头。

In situations where the system needs more memory it may kill paused processes to reclaim resources. 在系统需要更多内存的情况下,它可能会杀死暂停的进程以回收资源。 Because of this, you should be sure that all of your state is saved by the time you return from this function . 因此, 您应该确保在从此函数返回时保存所有状态 In general onSaveInstanceState(Bundle) is used to save per-instance state in the activity and this method is used to store global persistent data (in content providers, files, etc.) 通常onSaveInstanceState(Bundle)用于保存活动中的每个实例状态,此方法用于存储全局持久数据(在内容提供者,文件等中)

After receiving this call you will usually receive a following call to onStop() (after the next activity has been resumed and displayed), however in some cases there will be a direct call back to onResume() without going through the stopped state. 收到此调用后,您通常会收到以下对onStop()的调用(在下一个活动已恢复并显示之后),但在某些情况下,将直接回调onResume()而不会经历停止状态。

Derived classes must call through to the super class's implementation of this method. 派生类必须调用超类的此方法的实现。 If they do not, an exception will be thrown. 如果他们不这样做,将抛出异常。

I do recommend this flowchart for you it will help your development tremendously: 我建议您使用此流程图,它将极大地帮助您的开发:

Android活动流程图

It probably doesn't matter, but to know for sure, you need to know what the super methods are doing, and usually that information is not available to you. 它可能无关紧要,但要确切知道,您需要知道超级方法正在做什么,并且通常您无法获得这些信息。

My style is to call eg super.onCreate(), super.onResume(), etc. before the body of my own method, and eg super.onPause() and super.onDestroy() after the body of my own method. 我的风格是在我自己的方法体之前调用例如super.onCreate(),super.onResume()等,例如在我自己的方法体之后调用super.onPause()和super.onDestroy()。

The theory behind this is that I like to let the super methods run first while building something up, just in case what I'm doing depends on what the superclass sets up first, and when tearing something down, I like to tear down my own stuff before the superclass tears down its stuff. 这背后的理论是,我喜欢让超级方法在构建内容时先运行,以防万一我正在做的事情取决于超类首先设置什么,当我撕下一些东西时,我喜欢拆掉我自己的东西。在超类之前撕下它的东西。

There's no right or wrong. 没有对错。 That depends on what you do on your implementation of these methods. 这取决于您在实施这些方法时所做的工作。 Sometimes you'll want the super to be before your code, and sometime after. 有时你会希望super在你的代码之前,以及之后的某个时间。

You can put it anywhere. 你可以把它放在任何地方。 First you have to understand the Activity life cycle. 首先,您必须了解活动生命周期。 Check the following link Here 请在此处查看以下链接

Download the demo and run it you will be clear 下载演示并运行它你会很清楚

Delving into the android code, you can find that the framework sets a flag called mcalled when you call super.onPause(). 深入研究android代码,你会发现当你调用super.onPause()时,框架会设置一个名为mcalled的标志。 This flag is later checked on resume by the framework. 稍后由框架在恢复时检查该标志。

if (!mCalled) {
            throw new SuperNotCalledException(
                "Activity " + mComponent.toShortString() +
                " did not call through to super.onResume()");
        }

All you need to do is make sure the call is made to super and you are good. 您需要做的就是确保拨打超级电话并且您很好。 No other precaution is necessary. 没有必要采取其他预防措施。

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

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