上下文,AsyncTask的和旋转的变化上下文、AsyncTask

由网友(用情深至到无情)分享简介:是它使用一个很好的做法 getApplicationContext()与AsyncTask的,以没有附加和分离活动的工作,以避免内存泄漏当发生轮换变化,在活动被破坏?我的东西就应该是正确的,因为我真的需要一个背景下,依赖于孔的应用,而不是活动本身。和更有甚者,在这些案件中,最好使用活动为背景(因为你需要访问活动的表现...

是它使用一个很好的做法 getApplicationContext()与AsyncTask的,以没有附加和分离活动的工作,以避免内存泄漏当发生轮换变化,在活动被破坏?我的东西就应该是正确的,因为我真的需要一个背景下,依赖于孔的应用,而不是活动本身。

和更有甚者,在这些案件中,最好使用活动为背景(因为你需要访问活动的表现)......而不是脱离它的(指定为null)当它被摧毁,然后分配在的onCreate的新实例(),可能只是避免拆卸?所以,仅仅reasigning新的实例,这这样,我们就能避免NullPointerException异常的问题,因为总会有一个上下文使用!

解决方案

从我自己的经验,我可以说,在大多数情况下,最好使用活动作为上下文,不是 getApplicationContext()当与的AsyncTask 。这是因为大多数的时候,你需要从你的Activity访问的成员,你将只被允许这样做,如果你有一个参考的活动在AsyncTask的。

要回答我的问题如何避免分离(),让我说,在这种情况下,你能避免它,或者只是做了没有任何问题,因为@CommonsWare状态。所以,从他说的话,我们相信,我们不会得到一个 NullPointerException异常而活动的旋转变化时为空:

  

onProgressUpdate()和onPostExecute()onRetainNonConfigurationInstance(开始之间暂停)和后续的onCreate的末端()

上下文聚合网络用于遥感影像语义分割

如果我没看错,不是分离明确,只是重新安装了新一期的主要区别在的onCreate()新创建活动的就是你在刚重新连接几毫秒后释放旧活动实例。但最终的行为是在两种情况下是相同

希望这可以帮助别人! :)

Is it a good practice to use getApplicationContext() working with AsyncTask in order to do not have to attach and detach the Activity to avoid memory leaks when rotation changes occur and the Activity is destroyed? I thing it should be correct, as I actually need a Context that depends on the hole application, not the Activity itself.

And what is more, in those cases in which is better to use the Activity as context (because you need access to the Activity showing)... Instead of detaching it (assigning to null) when it is destroyed and then assign the new instance in onCreate(), could be just avoid detaching? So, just reasigning the new instance, this way, we could avoid problems of NullPointerException because there would always be a context to use!

解决方案

From my own experience I can say that in most cases it is better to use Activity as your Context, than getApplicationContext() when dealing with AsyncTask. This is because most of times you will need to access members from your Activity and you will only be allowed to do so if you have a reference to the Activity in your AsyncTask.

To answer my question about avoiding detach(), let me say that in this case you can avoid it or just do it without any problems, as @CommonsWare states in his answer. So, from what he says we are sure that we will not get a NullPointerException while the Activity is null during a rotation change:

onProgressUpdate() and onPostExecute() are suspended between the start of onRetainNonConfigurationInstance() and the end of the subsequent onCreate()

If I am not wrong, the main difference between not detaching explicitly and just re-attaching the new one in the onCreate() of the newly created Activity is that you free the old Activity instance some milliseconds later when just reattaching. But the final behavior is the same in both cases!

Hope this helps someone else! :)