[英]How to periodically save location updates using async task?
目前,我正在嘗試定期收集位置更新,例如每10個樣本一次。 我正在使用arraylist收集它們,並在使用異步任務將它們傳遞給服務器后,在主UI線程中清除了arraylist。 在異步任務中,我正在從主UI加載arraylist。
問題是,即使在單獨的變量中,它也在清除異步任務中的arraylist。 如何保持活動同步。 我是否需要休眠主要活動,直到異步任務完成。 我不確定該變量。 有人可以解釋如何做嗎?
MainMapActivity(X){
locationupdate for every 1 min{
arraylist a;//this collects all location updates 10 samples each time
call asynctask b;
clear a;
}
asynctask b{
arraylist c = getall from a;
db= insert(c);//save a into database;
}
在主用戶界面中清除a會清除變量c。 我該如何預防? 僅在將所有數據保存后才清除變量c。
如果我想知道的是,那么可以,我們可以使用處理程序來解決您的問題。
在你的異步任務,做這樣的事情 -
private mLocations;
public MyTask(Handler mResponseHandler, List<Location> mLocations){
super();
this.mLocations = mLocations;
this.mResponseHandler = mResponseHandler;
}
在onPostExecute中,
onPostExecute(List<Location>){
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.i(TAG, "result = "+result);
if (mResponseHandler == null) return;
MyLocationData<Location> resultData = new MyLocationData<Location>();
if(result != null && result){
resultData.requestSuccessful = true;
resultData.responseErrorCode = 0;
}else{
resultData.requestSuccessful = false;
resultData.responseErrorCode = errorCode; //set this when result is null
}
android.os.Message m = android.os.Message.obtain();
m.obj = resultData;
mResponseHandler.sendMessage(m);
}
}
MyLocationData是其中保存所有相關數據的模型類。 可能是這樣的一類-
public class MyLocationData<Type> {
public Type response;
public int responseErrorCode;
public boolean requestSuccessful;
}
現在,在您的活動中,您可以獲取以下數據,
private Handler mExportHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
MyLocationData<Location> responseData = (MyLocationData<Location>) msg.obj;
// your logic for fetching new locations from responseData and using them in your activity
};
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.