一个用于同步远程数据库数据异步类AsyncTask
此类省略某些业务代码:
package com.abc.splashdemo;
//import ...;
import android.os.AsyncTask;
public class SyncCaseAsyncTask extends AsyncTask<String, Integer, String> {
public interface onSyncCompleted {
public void SyncCompleted();
}
private List<Case> listCases = new ArrayList<Case>();
private onSyncCompleted mOnSyncCompleted = null;
public SyncCaseAsyncTask() {
}
public void addCase(String strCaseGUID) {
//..
}
public void addCase(Case cs) {
//..
}
public void clear() {
listCases.clear();
}
public void setOnSyncCompleted(onSyncCompleted onSyncCompletedEventHandler) {
mOnSyncCompleted = onSyncCompletedEventHandler;
}
private boolean checkIsExist(String strCaseGUID) {
boolean rtn = false;
//..
return rtn;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//..
}
@Override
protected String doInBackground(String... params) {
if (listCases.size() > 0) {
//..
updateCase2Server(cs);
//..
return "同步完畢";
} else {
return "沒有參數";
}
}
private void updateCase2Server(Case cs) {
//..
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (mOnSyncCompleted != null) {
mOnSyncCompleted.SyncCompleted();
}
}
@Override
protected void onCancelled() {
super.onCancelled();
}
}
UI Activity的调用方法:
//--初始化--
private SyncCaseAsyncTask caseSyncTask = new SyncCaseAsyncTask();
//--增加事件处理--
caseSyncTask.setOnSyncCompleted(new onSyncCompleted() {
@Override
public void SyncCompleted() {
showMsg("--完成同步哦--");
caseSyncTask.clear();
}
});
//--调用--
if (caseSyncTask != null) {
caseSyncTask.addCase(new Case);
caseSyncTask.execute();
}
另外一个调用方法:可以多次调用,不过要等待异步执行完毕后,才从新手动执行,否则需要加一个
stopAyncTaskRunning(); 取消或者停止异步。
if (caseSyncTask == null) {
caseSyncTask = new SyncCaseAsyncTask();
caseSyncTask.addCase(mDatas.get(mPosition));
caseSyncTask.setOnSyncCompleted(SyncCompletedEventHandler);
caseSyncTask.execute();
}
SyncCompletedEventHandler = new onSyncCompleted() {
@Override
public void SyncCompleted() {
showMsg("--完成同步哦--");
caseSyncTask.clear();
caseSyncTask = null;
}
};
private void stopAyncTaskRunning() {
if (caseSyncTask != null && caseSyncTask .getStatus() == AsyncTask.Status.RUNNING) {
caseSyncTask .cancel(true);
//if task is still running, stop it;
}
}