Call different callback from AsyncTask onPostExecute()

眉间皱痕 提交于 2020-01-03 06:40:10

问题


I have implemented an internal AsyncTask for my class that does initial setup data query from server and stores into device cache. The setup data in split between 2 JSON files. The first JSON is read/cached and if certain conditions are on then second JSON file will be downloaded and stored into cache. I want to use same AsyncTask from both operations.

In doInBackground(), I perform JSON download operation independent of JSON type. But in onPostExecute() I want to call different callbacks depending if its 1st JSON file or second, since they require different handling. Is that possible?

EDIT: Pls note I do not want to use booleans, enum to decide which callback to call as in future I will have more files to process. From my calling class I want to set the callback and rest should happen automatically.


回答1:


Below implementation should solve your problem:

private class MyCustomAsyncTask extends AsyncTask<Void, Void, Void>{

        private boolean mShouldCallMethod1;

        public MyCustomAsyncTask(boolean shouldCallMethod1){
            mShouldCallMethod1 = shouldCallMethod1;
        }

        @Override
        protected Void doInBackground(Void... params) {
            //code goes here..
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if(mShouldCallMethod1){
                method1();
            }else{
                method2();  
            }
        }

    }

i.e have a customized AsyncTask as innerclass.




回答2:


If you use the same interface which contains the two callbacks this is no problem. Simply declare an interface with 2 callback methods (json1, json2) and pass an instance of the interface to the AsyncTask. In your onPostExecute() you can call the callback(s).




回答3:


As android does not support setListner Methods for onPostExccute so there is two ways:

  1. Extend AsychTask and imlement setOnPostExcuteListner
  2. Or just call "your method" from onPostExcute simple!


来源:https://stackoverflow.com/questions/21907478/call-different-callback-from-asynctask-onpostexecute

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