Android:重写onPause和onResume——正确的方式

时间:2021-12-26 23:41:15

When overriding the onPause() and the onResume() methods of the activity, where is the proper location to call the super.onPause() and super.onResume()? At the beginning of the method or at the end?

当重写该活动的onPause()和onResume()方法时,在哪里可以调用super.onPause()和super.onResume()?在方法的开始还是在结尾?

6 个解决方案

#1


15  

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. For other methods, it all depends on the semantics of the super class.

因此,对于生命周期回调,比如onPause()和onResume(),我们应该在一开始就执行super.onPause()或super.onResume()。对于其他方法,这完全取决于超类的语义。

#2


14  

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. 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. It has the documentation on its side.

更新:这是公认的答案,它包含了大量很好的信息,包括一个有用的图表,并将它们整合到一个地方。然而,它似乎是不正确的,至少根据当前的Android文档,正如海报所指出的,它是关于SDK的最终信息来源。在这个答案公布后,文件可能已经澄清。但是,无论如何,不要停止阅读这个答案,看看下面espinchi的答案。它有自己的文档。


Placement of the super methods depends only on your preference. 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. I bolded out the important parts:

我建议您阅读所有可用的文档,因为它们对您有很大的帮助。例如,这是在onPause javadoc中可以找到的。我删去了重要的部分:

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()之前,这个回调不会被创建,所以请确保在这里不要做任何冗长的事情。

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:重写onPause和onResume——正确的方式

#3


4  

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 e.g. super.onCreate(), super.onResume(), etc. before the body of my own method, and e.g. 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.

背后的理论是,我喜欢先让超级方法运行而建立起来的东西,以防我在做什么首先取决于超类设置,当撕裂下来的东西,我想推倒自己的东西在超类拆毁它的东西。

#4


3  

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在代码之前,或者之后。

#5


2  

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

下载演示并运行它,你将会清楚

#6


2  

Delving into the android code, you can find that the framework sets a flag called mcalled when you call super.onPause(). This flag is later checked on resume by the framework.

深入研究android代码,您可以发现,当您调用super.onPause()时,框架会设置一个名为mcall的标志。该标志稍后由框架在简历中检查。

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.

你所需要做的就是确保这个电话是打给super的,而且你做得很好。没有其他预防措施是必要的。

#1


15  

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. For other methods, it all depends on the semantics of the super class.

因此,对于生命周期回调,比如onPause()和onResume(),我们应该在一开始就执行super.onPause()或super.onResume()。对于其他方法,这完全取决于超类的语义。

#2


14  

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. 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. It has the documentation on its side.

更新:这是公认的答案,它包含了大量很好的信息,包括一个有用的图表,并将它们整合到一个地方。然而,它似乎是不正确的,至少根据当前的Android文档,正如海报所指出的,它是关于SDK的最终信息来源。在这个答案公布后,文件可能已经澄清。但是,无论如何,不要停止阅读这个答案,看看下面espinchi的答案。它有自己的文档。


Placement of the super methods depends only on your preference. 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. I bolded out the important parts:

我建议您阅读所有可用的文档,因为它们对您有很大的帮助。例如,这是在onPause javadoc中可以找到的。我删去了重要的部分:

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()之前,这个回调不会被创建,所以请确保在这里不要做任何冗长的事情。

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:重写onPause和onResume——正确的方式

#3


4  

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 e.g. super.onCreate(), super.onResume(), etc. before the body of my own method, and e.g. 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.

背后的理论是,我喜欢先让超级方法运行而建立起来的东西,以防我在做什么首先取决于超类设置,当撕裂下来的东西,我想推倒自己的东西在超类拆毁它的东西。

#4


3  

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在代码之前,或者之后。

#5


2  

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

下载演示并运行它,你将会清楚

#6


2  

Delving into the android code, you can find that the framework sets a flag called mcalled when you call super.onPause(). This flag is later checked on resume by the framework.

深入研究android代码,您可以发现,当您调用super.onPause()时,框架会设置一个名为mcall的标志。该标志稍后由框架在简历中检查。

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.

你所需要做的就是确保这个电话是打给super的,而且你做得很好。没有其他预防措施是必要的。