我正在制作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)
发布评论