弱引用get()方法有多安全? (Android,asynctask)

编程入门 行业动态 更新时间:2024-10-12 05:54:36
本文介绍了弱引用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)

本文发布于:2023-11-08 06:34:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568610.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有多   方法   asynctask   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!