我在6个不同的活动上有一个按钮。点击该按钮几乎完成相同的任务,具有不同的参数,具体取决于活动。
这将使用AsyncTask
完成,而onPostExecute()
按钮状态将会更改。
someButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Task().execute("param1", "param2");
}
}
private class Task extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
//background task using params[0], params[1]
return "success" or "error";
}
@Override
protected void onPostExecute(String result) {
if (result == "success") {
//change the someButton state
}else{
//show an error message
}
}
如何在所有6个活动中使用相同的AsyncTask,如何在所有活动中使用单个Asynctask并更改相应的视图?
答案 0 :(得分:1)
将您的Task
放入自己的文件中并将其公开。
创建一个回调接口:
public interface TaskCallback {
public void onSuccess(String result);
public void onFailure(String errorMessage);
}
向Task
发送回调:
public class Task extends AsyncTask<String, Void, String> {
private TaskCallback callback;
public Task(TaskCallback callback) {
this.callback = callback;
}
@Override
protected String doInBackground(String... params) {
//background task using params[0], params[1]
return "success" or "error";
}
@Override
protected void onPostExecute(String result) {
if (result == "success") {
callback.onSuccess(result);
} else{
callback.onFailure(errorMessage);
}
}
}
然后在您的活动中创建Task
实例时实施回调:
someButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
private TaskCallback callback = new TaskCallback() {
@Override
public void onSuccess(String result) {
//change the someButton state
}
@Override
public void onFailure(String errorMessage) {
//show an error message
}
}
new Task(callback).execute("param1", "param2");
}
}
答案 1 :(得分:1)
您应该创建Task,使用onSuccess,onFailure上的方法并覆盖它们。
public class Task extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
//background task using params[0], params[1]
return "success" or "error";
}
@Override
protected void onPostExecute(String result) {
if (result == "success") {
onSuccess(result);
}else{
onFailure(result);
}
}
protected void onSuccess(String result) {};
protected void onFailure(String result) {};
}
然后在活动中使用它:
someButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Task(){
@Override
protected void onSuccess(String result){
// do what you want
}
@Override
protected void onFailure(String result){
// do what you want
}
}.execute("param1", "param2");
}
}