Reputation: 8981
I want to accomplish to spawn a service every hour. This service should perform some SQL database operations. In order to do so, I've used AlarmManager like this:
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(Home.this, DeleteCaseService.class);
PendingIntent pintent = PendingIntent.getService(Home.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60*60*1000, pintent);
I haven't made the code for the service yet, but that's not the problem. My problem is kinda theoretical. If you imagine this app running for 8 hours constantly, will there will be started 8 different Service in 8 different threads? Or when will a service get killed? Is this the best approach? Feel free to suggest other solutions, but I want to keep the AlarmManager
Thanks.
Upvotes: 0
Views: 157
Reputation: 584
Instead of using service use broadcast receiver for making background operation on database to call the broadcast receiver use the bellow code
public class AlarmMgnr
{
private Intent intent;
Context context;
private static AlarmManager aMgnr;
private static PendingIntent sender;
public AlarmMgnr(Context context)
{
this.context = context;
}
public void registerAlarm()
{
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR);
cal.set(Calendar.HOUR, hour);
cal.set(Calendar.MINUTE, 00);
cal.set(Calendar.SECOND, 00);
System.out.println("AlarmMgnr.registerAlarm()");
intent = new Intent(context, <YourReciverCalssName>.class);
sender = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
aMgnr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// aMgnr.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, sender);
aMgnr.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 180000L, sender);
// aMgnr.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60000L, sender);
}
public void unregisterAlarm()
{
aMgnr.cancel(sender);
}
}
}
And start this alaram manage once only when application got installed .
Upvotes: 1