首先将异步任务及回调包装在一个controller类中
package com.example.zzz; import android.content.Context; import android.os.AsyncTask; public class BaseController { private Context ctx; private BaseControllerCallBack callback; /** * 构造函数 * @param ctx * @param BaseControllerCallBack callback */ public BaseController(Context ctx, BaseControllerCallBack callback){ this.ctx=ctx; this.callback=callback; } public void prepareTask(String param1,String param2,String param3){ new PrepareTask(param1,param2).execute(param3); } public void doTask(String param1,String param2,String param3){ new DoTask(param1,param2).execute(param3); } public class PrepareTask extends AsyncTask<String, Void, String>{ private String param1; private String param2; private String param3; public PrepareTask(String param1,String param2){ this.param1=param1; this.param2=param2; } @Override protected String doInBackground(String... params) { param3=params[0]; return test(param1,param2,param3); } @Override protected void onPostExecute(String result) { if(callback!=null){ callback.onPreparedDone(result); } } } public class DoTask extends AsyncTask<String, Void, String>{ private String param1; private String param2; private String param3; public DoTask(String param1,String param2){ this.param1=param1; this.param2=param2; } @Override protected String doInBackground(String... params) { param3=params[0]; return test(param1,param2,param3); } @Override protected void onPostExecute(String result) { if(callback!=null){ callback.onDoTaskDone(result); } } } //===============回调接口================// public interface BaseControllerCallBack{ /** * action1 * @param result */ public void onPreparedDone(String result); /** * action2 * @param result */ public void onDoTaskDone(String result); } private String test(String param1,String param2,String param3){ return "hello"; } }
在主程序中调用时
private void init() { controller=new BaseController(getApplicationContext(), callback); controller.prepareTask("11", "22", "33"); } private BaseControllerCallBack callback=new BaseControllerCallBack() { @Override public void onPreparedDone(String result) { controller.doTask("11", "22", "33"); } @Override public void onDoTaskDone(String result) { //dosomething } };
时间: 2024-10-29 11:34:45