Android: How to update an UI from AsyncTask if AsyncTask is in a separate class?

后端 未结 7 2122
半阙折子戏
半阙折子戏 2020-12-02 12:33

I hate inner class.

I\'ve a main activity who launches a \'short-life\' AsyncTask.

AsyncTask is in a separate file, is not an inner class of

7条回答
  •  不思量自难忘°
    2020-12-02 13:07

    AsyncTask is always separate class from Activity, but I suspect you mean it is in different file than your activity class file, so you cannot benefit from being activity's inner class. Simply pass Activity context as argument to your Async Task (i.e. to its constructor)

    class MyAsyncTask extends AsyncTask {
    
        WeakReference mWeakActivity;
    
        public MyAsyncTask(Activity activity) {
           mWeakActivity = new WeakReference(activity);
        }
    
     ...
    

    and use when you need it (remember to NOT use in during doInBackground()) i.e. so when you would normally call

    int id = findViewById(...)
    

    in AsyncTask you call i.e.

    Activity activity = mWeakActivity.get();
    if (activity != null) {
       int id = activity.findViewById(...);
    }
    

    Note that our Activity can be gone while doInBackground() is in progress (so the reference returned can become null), but by using WeakReference we do not prevent GC from collecting it (and leaking memory) and as Activity is gone, it's usually pointless to even try to update it state (still, depending on your logic you may want to do something like changing internal state or update DB, but touching UI must be skipped).

提交回复
热议问题