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

自作多情 提交于 2019-12-10 18:47:34

问题


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

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


来源:https://stackoverflow.com/questions/47220320/how-to-trigger-a-background-service-in-android-on-specific-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!