I am trying to poll a given website periodically for information and then in turn update the UI in an Android app.
I have set something up similar to the following, but it just seems cumbersome. I guess my two specific questions would be:
-
Is the
view.post(new Runnable());necessary or are the broadcasts handled on the UI thread (allowing the AsyncTask to be executed directly since it must be done from the UI)? -
Is there any way to periodically start an AsyncTask (or something comparable) besides setting up the alarms and receiving the Intents?
Here is a simplified version of what I am running:
public class WebUpdates extends BroadcastReceiver
{
private AlarmManager am ;
private PendingIntent pi ;
private View view ;
private Context listener ;
public WebUpdates(Context listener, View view)
{
this.listener= listener;
this.view = view ;
am = (AlarmManager)listener.getSystemService(Context.ALARM_SERVICE) ;
pi = PendingIntent.getBroadcast((Context)listener, 0, new Intent("WEBUPDATE"), 0) ;
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 0, (long)15000, pi) ;
}
@Override
public void onReceive(Context context, Intent intent)
{
view.post(new Runnable() {
public void run()
{
new WebUpdateTask().execute() ;
}
}) ;
}
private class WebUpdateTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... v)
{
// bunch of web stuff...
}
public void onPostExecute(Void v)
{
view.doBunchOfUpdates() ;
}
}
}
This is my first question, so I apologize for for any formatting issues. Any input or help would be much appreciated!
But I don’t think there is any harm in using AlarmManager even if you only need to update when your app is being used, as long as you cancel the alarm in onPause().