onboot 后台重复任务

Background repeating task with onboot

你好,我想做一个后台服务来更新我的应用程序的数据并每天重复一次,我还希望该服务在开机时启动。我有以下代码:

public class OnBoot extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Create Intent
        context.startService(new Intent(context, BackgroundServiceHandler.class));
    }

}

我有一个设置菜单,用户可以选择重复闹钟的时间。 如何重置警报管理器的时间?我必须在哪里放置警报管理器的代码?我必须使用服务或 intentservice 吗?如何检查服务是否为 运行?

报警管理器代码:

    Intent intent = new Intent(MainActivity.this, AlarmService.class);
    intent.putExtra("i", 3);
    PendingIntent pi = PendingIntent.getService(MainActivity.this, 9, intent, 0);

    // every day at 9 am
    Calendar calendar = Calendar.getInstance();

    // if it's after or equal 9 am schedule for next day
    if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) >= 9) {
        calendar.add(Calendar.DAY_OF_YEAR, 1); // add, not set!
    }
    calendar.set(Calendar.HOUR_OF_DAY, 9);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    alarmManager.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pi);
  • How can i reset the time of the alarmmanager?

How to edit/reset Alarm Manager?

  • Where i have to put the code of the alarm manager?

例如,您可以将该代码放在静态方法中,并从用户设置时间的地方和 OnBootReceiver 调用它。如何实现 class 接收事件 OnBoot 请检查 answer.

  • Do i have to use service or intentservice?

Service vs IntentService

  • How to check if service is running?

Check if service is running on Android?