Weakreference get() method how safe is it? (Android, asynctask)

六月ゝ 毕业季﹏ 提交于 2019-12-03 17:13:42

问题


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.

When onPostExecute() gets called, I do

Acitivty activity = mWeakRef.get();

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

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.

thanks!


回答1:


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.




回答2:


I think it's NOT safe. I get a NPE at activity.msgWebView.setVisibility(View.GONE); inside Handler.

```java

private static class HttpStatusHandler extends Handler {

    private WeakReference<MessageWebViewActivity> activityWeakReference;

    public HttpStatusHandler(WeakReference<MessageWebViewActivity> activityWeakReference) {
        this.activityWeakReference = activityWeakReference;
    }

    @Override
    public void handleMessage(Message msg) {
        MessageWebViewActivity activity = activityWeakReference.get();
        if (activity != null) {
            if (msg.what == MSG_URL_OK) {
                activity.loadUrl(activity.url);
            } else if (msg.what == MSG_URL_ERROR) {
                activity.msgWebView.setVisibility(View.GONE);
                activity.clPageError.setVisibility(View.VISIBLE);
                activity.progressbarLayout.setVisibility(View.GONE);
            }

        }
    }
}

```



来源:https://stackoverflow.com/questions/7048264/weakreference-get-method-how-safe-is-it-android-asynctask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!