我有多个活动和一个asyncTask,它们对如下所示的回调方法使用相同的接口
public interface AsyncTaskCallback {
void onCookie(CookieManager cookieManager);
void onResponse(String response);
void onProgress(String... values);
void onError(Exception e);
}
public void exec_taskt() {
alertDialog.SetText("Sending Request...");
AsyncTask1 task1 = new AsyncTask1("https://stackoverflow.com");
task1.setCookieManager(cookiejar);
task1.setCallback(this);
task1.execute();
}
@Override
public void onCookie(CookieManager cookieManager) {
cookiejar = cookieManager;
}
@Override
public void onResponse(String response) {
try {
PostProc(response);
}catch (Exception e){ // ERROR HERE
e.printStackTrace();
}
}
@Override
public void onProgress(String... values) {
alertDialog.SetText(values[0]);
}
@Override
public void onError(Exception e) {
///SAME ERROR HERE TOO
//Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
swipeRefreshLayout.setRefreshing(false);
}
private void PostProc(String response) {
//the response string is parsed and displayed in a recyclerview in this method
//this method is slightly different for each activity
}
public class AsyncTask1 extends AsyncTask<String, String, String> {
private String address = "";
private CookieManager mCookieManager;
private Exception mException;
private AsyncTaskCallback mCallback;
public AsyncTask1 (String page) {
this.address = page;
}
public void setCookieManager(CookieManager cm) {
this.mCookieManager = cm;
}
public void setCallback(AsyncTaskCallback cb) {
this.mCallback = (AsyncTaskCallback) cb;
}
@Override
protected String doInBackground(String... strings) {
try{
//all code here is executed without error
//code skipped for simplicity
// basically just loads the given url and then...
publishProgress("Page Loaded");
mCallback.onCookie(mCookieManager);
mCallback.onResponse(response);
return response;
} catch (Exception e) {
publishProgress("Error");
e.printStackTrace();
mCallback.onError(e);
return "";
}
@Override
protected void onProgressUpdate(String... values) {
Log.d(tag, TextUtils.join(",", values));
mCallback.onProgress(values);
super.onProgressUpdate(values);
}
}
标记为我得到的错误
这里有错误
在上面的代码中。消息如下
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
我的主要怀疑对象是与UI组件一起玩的活动中的PostProc()
方法。但是,在活动中实现接口是否意味着部分代码在主UI线程中运行?我知道您可以将活动实例传递给asyncTask并从asyncTask的后执行中调用PostProc()
方法,但是我想探索一种替代方法,因为其他活动也可以访问相同的asynctask。所有活动的收益都是相同的。仅PostProc
方法不同。
提前感谢
代替使用callback interface
,可以使用与android.os.Handler()
关联的MainLooper
来更新视图,例如:-