将接口传递给AsyncTask是一种很好的做法

laa*_*ptu 0 android interface android-asynctask

我有一个接口类

public interface AsyncTaskExecuteCommand {
public Object executeCommand(String jsonLocation) throws IOException,JSONException;
}
Run Code Online (Sandbox Code Playgroud)

我有一个存储此接口实例的HashMap

public static HashMap<String,AsyncTaskExecuteCommand> executeCommandHashMap

executeCommandHashMap.put(COMMAND_CORE_FIELD_FETCH, new AsyncTaskExecuteCommand() {
        @Override
        public Object executeCommand(String jsonLocation) throws IOException, JSONException{
                           //return some thing
        }
    });

executeCommandHashMap.put(COMMAND_REGISTER_FIELD_FETCH, new AsyncTaskExecuteCommand() {
        @Override
        public Object executeCommand(String jsonLocation) throws IOException,
                JSONException {
                          //return some thing
        }
    });
Run Code Online (Sandbox Code Playgroud)

我的AsyncTask名为GeneralAsyncTask包含

doInBackground(){

 AsyncTaskExecuteCommand asyncTaskExecuteCommand = executeCommandHashMap.get(params[0]);
 return asyncTaskExecuteCommand.executeCommand(params[1]);
}
Run Code Online (Sandbox Code Playgroud)

而这个AsyncTask被调用

new GeneralAsyncTask().execute(COMMAND_REGISTER_FIELD_FETCH,"http://something");
Run Code Online (Sandbox Code Playgroud)

我这样做是因为我的AsyncTask的一般结构保持不变,即它做了一些方法执行并返回一些值.只有方法执行类型和返回值会有所不同.如果我不实现传递接口到异步任务,我最终创建了许多AsyncTask类.那么,这种方法是否可以解决我的问题?

Sha*_*zon 5

似乎很复杂.有没有理由你不使用匿名类:

new AsyncTask<String, Void, Object>() {
    @Override
    protected Object doInBackground(String... url) {
        //return some thing
    }
    protected void onPostExecute(Object result) {
        // do something with result
    }
}.execute("http://something");
Run Code Online (Sandbox Code Playgroud)