I\'m refactoring some code so that my app will pull data from a website once a day at a given time. From my research, it seems like AlarmManager
is the most app
You could get AlarmManager to run the Service straight away rather than going through a BroadcastReceiver, if you change your intent like this:
//Change the intent
Intent downloader = new Intent(context, MyService.class);
downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//Change to getService()
PendingIntent pendingIntent = PendingIntent.getService(context, 0, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
This may solve your problem!
Instead of using
Intent dailyUpdater = new Intent(context, MyService.class);
use
Intent dailyUpdater = new Intent(this, MyService.class);
Other suggestion is to start service directly from alarm rather than sending a broadcast and starting the service in broadcast receiver.
Figured it out!
MyService should be extending IntentService instead of Service!
With this change, it also means that instead of overriding onStartCommand
should be overriding onHandleIntent
instead (see docs on IntentService)
So MyService now looks like this:
public class MyService extends IntentService {
public MyService() {
super("MyServiceName");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d("MyService", "About to execute MyTask");
new MyTask().execute();
}
private class MyTask extends AsyncTask<String, Void, boolean> {
@Override
protected boolean doInBackground(String... strings) {
Log.d("MyService - MyTask", "Calling doInBackground within MyTask");
return false;
}
}
}
Note: From the docs, the default implementation of onBind
returns null
so no need to override it.
More information about extending IntentService
: http://developer.android.com/guide/topics/fundamentals/services.html#ExtendingIntentService