问题
I want to load data from server synchronously and show it in a view like ListView
or TextView
without any pulling request each time. I need the data will be loaded if there is any changes in server.
Right now I am using asynctask to pull data from server but to load new data or update I need to do pulling request using a reload button.
I tried it using a thread which will run after a certain time. But I know there might have some better method obviously.
How can I do the same thing without the manual pulling request?
For example gmail app loads new emails when there is network access without any pulling request from user. I need the same thing in my Android Application.
Thanks in advance.
回答1:
public void callAsynchronousTask() {
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 {
PerformBackgroundTask performBackgroundTask = new PerformBackgroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 50000); //execute in every 50000 ms
}
The AsyncTask
does run on a separate thread, but cannot be started from other threads than the UI thread
. The handler is there for allowing that.
来源:https://stackoverflow.com/questions/39498403/check-and-pull-data-from-server-continuously-in-android-application