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

后端 未结 2 1560
你的背包
你的背包 2021-02-06 00:19

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() g

2条回答
  •  孤街浪徒
    2021-02-06 00:40

    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 activityWeakReference;
    
        public HttpStatusHandler(WeakReference 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);
                }
    
            }
        }
    }
    

    ```

提交回复
热议问题