Question

I am using Android AlarmManger to schedule an IntentService to run after small intervals.

Here is my AlarmManger:

static void setNextSchedule(Context ctx, long interval){
        AlarmManager manager = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
        Intent nIntent = new Intent(ctx, DService.class);
        PendingIntent pIntent = PendingIntent.getActivity(ctx, 1, nIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        manager.setRepeating(AlarmManager.ELAPSED_REALTIME, 
                SystemClock.elapsedRealtime() + interval, interval, pIntent);

        Log.i(ScheduleAlarm.class.getSimpleName(), "Next alarm set");
    }

And my IntentService:

@Override
    protected void onHandleIntent(Intent intent) {
        Log.i(DService.class.getSimpleName(), "Service starting");

        ScheduleAlarm.setNextSchedule(getApplicationContext(), 15000);
    }

Currently it just holds code for testing. Now this code will run successfully with no problems once the app starts but after 15 seconds it will state that the service is starting in the logcat but the code won't execute.

How to get the intenet service the execute the code inside the onHandleIntent each time it runs?

Thanks

Was it helpful?

Solution

When using a PendingIntent, the factory method needs to match the type of component that your Intent is for:

  • If your Intent points to an activity, use getActivity()

  • If your Intent points to a service, use getService()

  • If your Intent points to a BroadcastReceiver, use getBroadcast()

  • If your Intent points to none of the above, go directly to jail, do not pass Go!, do not collect $200 :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top