弱引用get()方法有多安全? (Android,asynctask) [英] Weakreference get() method how safe is it? (Android, asynctask)

查看:103
本文介绍了弱引用get()方法有多安全? (Android,asynctask)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作Android移动应用。我在AsyncTask中对我的Activity有一个WeakReference以确保它可以被垃圾收集。

I am making an Android mobile app. I have a WeakReference to my Activity in the AsyncTask to ensure that it can be garbage collected.

onPostExecute()被叫,我做了

Acitivty activity = mWeakRef.get();

然后我使用活动对象向用户显示对话框等。

Then I use the activity object to display dialogs to the user etc etc.

我的问题是,当我试图确定要显示哪个对话框以及要做什么时,我的活动对象可能变为空吗?如果GC在我的执行行之间运行,它会变为null吗?我可以安全地从第一个 get()继续使用该对象,或者我是否必须重做 get()并且在我使用它之前检查值是否为空。

My question is, as I am trying to determine which dialog to show and what to do, could my activity object become null? Could it ever become null if the GC runs in between my line of execution? Am I safe to keep using that object from the first get() or do I have to redo get() and check if the value is null right before I use it.

谢谢!

推荐答案

这是安全的!

只要将get()的结果赋给变量,只要新引用存在,您就会再次使用强引用来阻止此对象的gargbage集合。

当然,在这项任务之后你需要检查活动是否为空。

It's safe!
As soon as you assign the result of get() to a variable, you have a strong reference again which blocks gargbage collection for this object as long as the new reference exists.
Of course, after this assignment you need to check if activity is null.

这篇关于弱引用get()方法有多安全? (Android,asynctask)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆