选项 1。上移:
clearDb();
dataList = fetchDataFromHttp();
saveToDb(dataList);
在与类对象同步的单独类中:
public class WorkerClass {
private WorkerListener workerListener;
public static interface WorkerListener {
public void publishWorkProgress(String data);
}
public WorkerClass(WorkerListener workerListener) {
this.workerListener = workerListener;
}
public void performWork() {
synchronized (WorkerClass.class) {
clearDb();
publish("Cleared DB");
dataList = fetchDataFromHttp();
publish("Got http data");
saveToDb(dataList);
publish("There! saved!");
}
}
private void publish(String message) {
if(workerListener != null) {
workerListener.publishWorkProgress(message);
}
}
}
在您的活动中:
public class SampleActivity extends Activity {
public void doTheThing() {
new MyAsyncTask().execute();
}
private static class MyAsyncTask extends AsyncTask<Void, String, Void> implements WorkerListener {
@Override
protected Void doInBackground(Void... params) {
new WorkerClass(this).performWork();
return null;
}
@Override
public void publishWorkProgress(String data) {
publishProgress(data);
}
}
}
选项 2:将上述代码移至 IntentService:
public class WorkerIntentService extends IntentService {
public WorkerIntentService() {
super(null);
}
@Override
protected void onHandleIntent(Intent intent) {
clearDb();
dataList = fetchDataFromHttp();
saveToDb(dataList);
}
}
使用 IntentService 可以保证任务是按顺序执行的。