我有一个asynctask获取服务器的位置并生成一个标记,asynctask在OnCreate()中运行一次并且工作正常但我需要每分钟运行它,我读到我需要使用计时器但我不了解如何实现它,继承asynctask:
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set json string url
String yourJsonStringUrl = url;
JSONArray dataJsonArr = null;
@Override
protected void onPreExecute() {}
@Override
protected String doInBackground(String... arg0) {
try {
// instantiate json parser
LatLngActivity jParser = new LatLngActivity();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray(ID_CAMION);
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing JSON item in a Variable
String JSON_latitude = c.getString(TAG_LATITUDE);
String JSON_longitude = c.getString(TAG_LONGITUDE);
//converting JSON variables in double variables
double HTTP_latitude = Double.parseDouble(JSON_latitude);
double HTTP_longitude = Double.parseDouble(JSON_longitude);
HTTP_list.add(HTTP_latitude);
HTTP_list.add(HTTP_longitude);
// show the values in logcat
Log.e(TAG, "latitude: " + HTTP_list.get(0)
+ ", longitude: " + HTTP_list.get(1)
);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result){
createHTTPmarker();
}
}
答案 0 :(得分:9)
Timer
使用TimerTask
。在Activity
中定义以下方法:
private void setRepeatingAsyncTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
AsyncTaskParseJson jsonTask = new AsyncTaskParseJson();
jsonTask.execute();
} catch (Exception e) {
// error, do something
}
}
});
}
};
timer.schedule(task, 0, 60*1000); // interval of one minute
}
现在从您的setRepeatingAsyncTask()
或onCreate()
致电onResume()
。