AlarmManager, BroadcastReceiver and Service not working

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 appropriate approach.

The tutorial I have been following is: http://mobile.tutsplus.com/tutorials/android/android-fundamentals-downloading-data-with-services/

  • How to use PendingIntent to communicate from a Service to a client/Activity?
  • SQLite Database gives warning automatic index on <table_name>(column) After upgrading Android L
  • Not able to make xmpp connection between my app server and GCM's CCS using XMPPHP library
  • how to get text from autocomplete textview android
  • Get application context from non activity singleton class
  • Receiving a build error when upgrading to gradle 3.3 and android build tools 2.3.0
  • So far, AlarmManager and the BroadcastReceiver seem to be working, however the Service never seems to start (ie. onStartCommand doesn’t seem to be called)

    Here are the important snippets of the code I have so far:

    MyActivity.java

    private void setRecurringAlarm(Context context) {
        Calendar updateTime = Calendar.getInstance();
        updateTime.setTimeZone(TimeZone.getDefault());
        updateTime.set(Calendar.HOUR_OF_DAY, 20);
        updateTime.set(Calendar.MINUTE, 30);
    
        Intent downloader = new Intent(context, AlarmReceiver.class);
        downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        // should be AlarmManager.INTERVAL_DAY (but changed to 15min for testing)
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent); 
        Log.d("MyActivity", "Set alarmManager.setRepeating to: " + updateTime.getTime().toLocaleString());
    }
    

    AlarmReceiver.java

    public class AlarmReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Intent dailyUpdater = new Intent(context, MyService.class);
            context.startService(dailyUpdater);
            Log.d("AlarmReceiver", "Called context.startService from AlarmReceiver.onReceive");
        }
    }
    

    MyService.java

    public class MyService extends Service {
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.d("MyService", "About to execute MyTask");
            new MyTask().execute();
            return Service.START_FLAG_REDELIVERY;
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        private class MyTask extends AsyncTask<String, Void, boolean> {
            @Override
            protected boolean doInBackground(String... strings) {
                Log.d("MyService - MyTask", "Calling doInBackground within MyTask");
                return false;
            }
        }
    }
    

    AndroidManifest.xml

    <application ...>
        ...
        <service android:name="MyService"></service>
        <receiver android:name="AlarmReceiver"></receiver>
    </application>
    

    When I trigger the setRecurringAlarm in MyActivity the log prints as expected, similarly, every 15min the log from AlarmReceiver appears. However, I never see the log from MyService 🙁

    Example of what I see in the logs:

    DEBUG/MyActivity(688): Set alarmManager.setRepeating to: Jan 29, 2012 8:30:06 PM
    DEBUG/AlarmReceiver(688): Called context.startService from AlarmReceiver.onReceive
    DEBUG/AlarmReceiver(688): Called context.startService from AlarmReceiver.onReceive
    

    Can’t seem to figure out what I’ve done wrong – my understanding from the Android Dev Docs is that in AlarmReceiver when I call context.startService(dailyUpdater) that should in turn call onStartCommand in MyService, though that doesn’t seem to be the case!

    What am I doing wrong that is causing MyService to not start at all?

  • Make activity animate from top to bottom
  • Detect when videoview stops playing
  • Distributing Android apps outside of the Android Market
  • Android one OnClick method for multiple buttons?
  • Is it ok to save a JSON array in SharedPreferences?
  • How to create an Android Activity and Service that use separate processes
  • 3 Solutions collect form web for “AlarmManager, BroadcastReceiver and Service not working”

    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

    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.

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.