如何在特定时间触发android中的后台服务?

时间:2017-11-10 10:10:49

标签: android background-service

我知道如何在特定时间触发android中的后台服务。我已经使用AlarmManager来实现这一目标,但我希望每天都能启动该服务。

假设我想在中午12点开始,但服务应该继续下去。我也使用了stopitself()方法,但这不起作用。

这是我的代码:

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 个答案:

答案 0 :(得分:1)

您好请使用此代码,这将有助于满足您的愿望。

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