See the Upgrade section below for my modified solution.
purpose
- Periodically poll URLs (for example, every 30 seconds), but only when activity is in the foreground
- Stop polling if activity is not in the foreground.
Periodic execution
- A handler object that receives a Runnable using a method
postDelayed runAsyncTask is launched in the Runnable object method- In
onPostExecuteAsyncTask, the postDelayedHandler object object is called again - In
onResumeactivity, the postHandler object method is called - In
onPauseactivity, the removeCallbacksHandler object is invoked to remove pending Runnable messages in the message queue
Problem with poll cancellation
- Runnable
onPause, , AsyncTask, doInBackground, Runnable onPostExecute ( , removeCallbacks onPause)
- โโ boolean member
shouldPoll - true
onResume, false - onPause onPostExecute AsyncTask , shouldPoll postDelayed Handler
shouldPoll OK?- , - (, ,
shouldPoll) ; , - AsyncTask onPostExecute
MainActivity
boolean shouldPoll = false;
@Override
protected void onResume() {
super.onResume();
shouldPoll = true;
handler.post(pollURLRunnable);
}
@Override
protected void onPause() {
shouldPoll = false;
handler.removeCallbacks(pollURLRunnable);
super.onPause();
}
final Handler handler = new Handler();
final Runnable pollURLRunnable = new Runnable() {
public void run() {
PollingAsyncTask pollTimestampAsyncTask = new PollingAsyncTask();
pollTimestampAsyncTask.execute();
}
};
AsyncTask
@Override
protected void onPostExecute(Result result) {
if (result != null) {
}
if (shouldPoll) {
handler.postDelayed(pollURLRunnable, 10000);
}
}
Update
MainActivity
@Override
protected void onResume() {
super.onResume();
handler.post(startIntentServiceRunnable);
LocalBroadcastManager.getInstance(this).registerReceiver(statusBroadcastReceiver, new IntentFilter(Constants.MY_INTENT_FILTER));
}
@Override
protected void onPause() {
handler.removeCallbacks(startIntentServiceRunnable);
LocalBroadcastManager.getInstance(this).unregisterReceiver(statusBroadcastReceiver);
super.onPause();
}
final Handler handler = new Handler();
final Runnable startIntentServiceRunnable = new Runnable() {
public void run() {
Intent intent = new Intent(MainActivity.this, PollingService.class);
startService(intent);
}
};
final BroadcastReceiver statusBroadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
handler.postDelayed(startIntentServiceRunnable, 2000);
}
};
PollingService
@Override
protected void onHandleIntent(Intent intent) {
broadcastResults();
}
private void broadcastResults() {
Intent intent = new Intent(Constants.MY_INTENT_FILTER);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}