上下文、AsyncTask 和轮换更改
使用 getApplicationContext()
与 AsyncTask 配合使用,以便不必附加和分离 Activity 来避免内存泄漏时 发生旋转变化并且活动被破坏?我认为它应该是正确的,因为我实际上需要一个依赖于洞应用程序的上下文,而不是活动本身。
更重要的是,在这些情况下,最好使用 Activity 作为上下文(因为您需要访问显示的 Activity)...而不是在它发生时分离它(分配给 null)销毁,然后在onCreate()
中分配新实例,可以避免分离吗?所以,只需重新分配新实例,这样,我们就可以避免 NullPointerException 的问题,因为总会有一个上下文 使用!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这篇文章及其答案很好地解释了要做什么。 这篇文章及其答案解释了 AsyncTask 和 Context 问题背后的一些很好的理论。
This post and its answers are a good explanation of what to do. This post and its answers explain some good theory behind the
AsyncTask
andContext
issue.根据我自己的经验,我可以说,在大多数情况下,在处理
Activity
时,最好使用Activity
作为Context
,而不是getApplicationContext()
。代码>异步任务。这是因为大多数时候您需要从 Activity 访问成员,并且只有在 AsyncTask 中有对 Activity 的引用时才允许您这样做。为了回答我关于避免
detach()
的问题,我想说的是,在这种情况下,您可以避免它,或者只是毫无问题地执行它,正如 @CommonsWare 所说的 在他的回答中。因此,根据他的说法,我们确信在旋转更改期间 Activity 为 null 时我们不会收到 NullPointerException:如果我没记错的话,不显式分离和仅在
中重新附加新的之间的主要区别新创建的 Activity 的 >onCreate()
是指在重新附加时几毫秒后释放旧的 Activity 实例。但两种情况下的最终行为是相同的!希望这对其他人有帮助! :)
From my own experience I can say that in most cases it is better to use
Activity
as yourContext
, thangetApplicationContext()
when dealing withAsyncTask
. 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 aNullPointerException
while the Activity is null during a rotation change: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! :)