我应该实现onRetainNonConfigurationInstance?onRetainNonConfigurationInstance

2023-09-07 22:03:11 作者:左学霸右校草

我刚刚看了一下我保持Android应用程序的状态,并偶然发现onRetainNonConfigurationInstance。不过,虽然读documentation我注意到这句话:

I just read about maintaining state of my android app and stumbled upon onRetainNonConfigurationInstance. But while reading the documentation I noticed this sentence:

此功能纯粹是称为优化,你必须不依赖于它被调用。

This function is called purely as an optimization, and you must not rely on it being called.

所以我想知道:确实,当它真的有意义使用此方法。如果我不能依靠它被调用,我需要另一种机制来传送无论如何状态(这在我的情况下,会出现一些序列化)。所以,除非我遇到任何性能命中,没有任何理由为什么我应该去onRetainNonConfigurationInstance?

So I wonder: when does it really make sense to use this method. If I cannot rely on it being called, I need another mechanism to transfer state anyway (which in my case would be some serialization). So unless I experience any performance hits, is there any reason why I should go for onRetainNonConfigurationInstance?

如果将它保证被调用,我很乐意使用它,但如果它不是,它似乎pretty没用的。

If it would be guaranteed to be called, I'd love to use it, but if it's not, it seems pretty useless.

我缺少的东西吗?当你用这种方法?你将如何保持网络连接,或者类似的事情?

Am I missing something? When do you use this method? How would you keep a network connection or things like that?

谢谢!

推荐答案

什么是文件的意思是,有一些情况时,活动不会立即重新创建,在这种情况下onRetainNonConfigurationInstance()将不会被调用。你不能用这个方法坚持数据。它仅用于传输是一个配置改变期间创建昂贵对象

What the documentation mean is that there are cases when the Activity will not be recreated immediately, in which case onRetainNonConfigurationInstance() will not be called. You cannot use this method to persist data. It is only used to transfer objects that are expensive to create during a configuration change.