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

后端 未结 7 2072
半阙折子戏
半阙折子戏 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:14

    I wrote a small extension to AsyncTask for this kind of scenario. It allows you to keep your AsyncTask in a separate class, but also gives you convenient access to the Tasks's completion:

    public abstract class ListenableAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result>{
    
        @Override
        protected final void onPostExecute(Result result) {
            notifyListenerOnPostExecute(result);
        }
    
        private AsyncTaskListener<Result> mListener;
        public interface AsyncTaskListener<Result>{
            public void onPostExecute(Result result);
        }
        public void listenWith(AsyncTaskListener<Result> l){
            mListener = l;
        }
        private void notifyListenerOnPostExecute(Result result){
            if(mListener != null)
                mListener.onPostExecute(result);
        }
    
    }
    

    So first you extend ListenableAsyncTask instead of AsyncTask. Then in your UI code, make a concrete instance and set listenWith(...).

    0 讨论(0)
提交回复
热议问题