Reputation: 288
I am trying to figure this out for a while now.
In my activity I have set an alarm manager to trigger every 2 mins(for testing) and invoke a service via a receiver. The service is suppose to make network calls etc.
My problem is the AlarmManager triggers the first time correctly but never triggers it again. What did I miss?
In my activity I do this -
//Register an alarm manager
//If no alarm is set
Intent alarmIntent = new Intent(context, AlarmReceiver.class);
alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
if(!defaultSharedPref.getBoolean("isAlarmSet",false)){
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
R.string.interval,
pendingIntent);
editor = defaultSharedPref.edit();
editor.putBoolean("isAlarmSet",true);
editor.commit();
}
In my manifest:-
<receiver android:process=":remote" android:name=".receiver.AlarmReceiver" />
<service android:name=".service.AlarmService"/>
My receiver :-
public class AlarmReceiver extends WakefulBroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, AlarmService.class);
startWakefulService(context,i);
}
}
I even tried the "setRepeating" but no luck. It still triggers only once. Can someone point out where I missed something?
Thanks in advance.
Upvotes: 0
Views: 940
Reputation: 9285
As the interval for your repeating timer you are giving a resource id - R.string.interval. This doesn't make sense, but will compile since it's an integer. If you want your interval as a resource, you'd be better of using an integer resource, but the most crucial change you need is to pass the actual value of the resource rather than the resource id. So for this, use Resources.getInteger or getString.
This should work, however I encourage you not to use a string resource at all:
manager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
Integer.parseInt(getResources().getString(R.string.interval)),
pendingIntent);`
The reason you aren't seeing any triggered alarms in practice is that resource ids are very large integers, typically in the 0x8000000 range, so you're effectively setting a recurrent alarm with a very very long interval. If you wait for a month or so, the alarm would be triggered. :-)
Upvotes: 1
Reputation: 888
If you want a more flexible way to schedule jobs, I would recommend this library that abstracts for you the used scheduler: https://github.com/evernote/android-job
Upvotes: 0