問題描述
在後台android更新數據到服務器 (update data to server in the background android)
How to update data to server ? I have used the code below but its not executing after 10 mins.
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(new Runnable(){
public void run() {
//update data to server
}
}, 0, 600, TimeUnit.SECONDS);
‑‑‑‑‑
參考解法
方法 1:
You must use your own Thread. Here is solution using AsyncTask....
All code put in your Activity class.
public void toCallAsynchronous() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
MyAsyncTask task = new MyAsyncTask();
task.execute(txtSearchField.getText().toString());
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 2000); // execute in every 2 second
}
// AsyncTask Class
private class MyAsyncTask extends AsyncTask<String, Object, List<ModelObject>> {
@Override
protected List< ModelObject > doInBackground(String... params) {
// Call web service
return null;
}
@Override
protected void onPostExecute(List< ModelObject > result) {
super.onPostExecute(rezultat);
// Update UI
}
}
方法 2:
Try with this
private static final ScheduledExecutorService worker = Executors
.newSingleThreadScheduledExecutor();
worker.schedule(new Runnable(){
public void run() {
//update data to server
}, 600, TimeUnit.SECONDS);
(by James Patrick、Haris Dautović、Jambaaz)