3

I know how to trigger a background service in android even on specific time. I have used AlarmManager to achieve this, but I want to start that service daily on that time.

Suppose I want to start it on 12pm, but the service should keep going on after that. I have also used the stopitself() method, but that does not work.

Here is my code:

void alram(Context ctx){

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());
    cal.set(Calendar.HOUR_OF_DAY, 12);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.AM_PM,Calendar.AM);

    Intent serviceIntent = new Intent(ctx, ServiceClass.class);
    PendingIntent servicePendingIntent =
        PendingIntent.getService(ctx,Service_Apps.SERVICE_ID,serviceIntent,0);

    AlarmManager alarm = (AlarmManager) ctx
        .getSystemService(Context.ALARM_SERVICE);
    alarm.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),servicePendingIntent);
    alarm.setRepeating(
        AlarmManager.RTC_WAKEUP,
        cal.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY,
        servicePendingIntent
    );
}
Keale
  • 3,924
  • 3
  • 29
  • 46
  • 3
    Possible duplicate of [Using Alarmmanager to start a service at specific time](https://stackoverflow.com/questions/3052149/using-alarmmanager-to-start-a-service-at-specific-time) – Channa Nov 10 '17 at 10:15
  • have look https://stackoverflow.com/questions/8321443/how-to-start-service-using-alarm-manager-in-android – Hemant Parmar Nov 10 '17 at 10:28
  • @Channa no its not dupplicate , we can start service on specific time , but i am looking for daily basis . – Abhishek Nov 10 '17 at 11:06
  • What you can do is plan new .setExact(..) for next day when you execute "old" one. So your Intent will do work+schedule. – Tomas Ivan Nov 10 '17 at 11:41

1 Answers1

1

Hi Please use this code it will help to fill your desires.

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12); 
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = PendingIntent.getService(this, 0,
        new Intent(this, Service_Apps.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY, pi);
Keale
  • 3,924
  • 3
  • 29
  • 46
Abhishek
  • 682
  • 6
  • 17