【问题标题】:How to trigger a background service in android on specific time?如何在特定时间触发android中的后台服务?
【发布时间】:2017-11-10 10:10:49
【问题描述】:

我知道如何在特定时间触发 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
    );
}

【问题讨论】:

标签: android background-service


【解决方案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);

【讨论】:

    猜你喜欢
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多