简体   繁体   中英

How to trigger a background service in android on specific time?

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
    );
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM