问题
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:
- Extend AsychTask and imlement setOnPostExcuteListner
- Or just call "your method" from onPostExcute simple!
来源:https://stackoverflow.com/questions/21907478/call-different-callback-from-asynctask-onpostexecute