在启动时以及每分钟创建后台服务 运行

Make Background Service run on startup as well as every minute

目前,我有一个 IntentService 检查 php 服务器是否有针对用户的新通知,以及一个侦听 BOOT_COMPLETED 的 BroadcastReceiver。我想知道的是如何将两者结合起来,不仅在启动时使 IntentService 运行,而且从那时起每分钟都使 IntentService 运行。

此外,我想确保以正确的方式发送通知。在 IntentService.onHandleIntent() 中,我有这个用于发送通知。

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_launcher).setContentTitle(title).setContentText(message);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(Integer.parseInt(id), mBuilder.build());

我是否遗漏了任何实际创建通知的内容? (变量 "title"、"message" 和 "id" 已设置)

对重复任务使用 AlarmManager。

// Setup a recurring alarm every half hour
  public void scheduleAlarm() {

    // Construct an intent that will execute the AlarmReceiver
    Intent intent = new Intent(getApplicationContext(), MyAlarmReceiver.class);

    // Create a PendingIntent to be triggered when the alarm goes off
    final PendingIntent pIntent = PendingIntent.getBroadcast(this, MyAlarmReceiver.REQUEST_CODE,
        intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Setup periodic alarm every 5 seconds
    long firstMillis = System.currentTimeMillis(); // alarm is set right away

    AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);

    // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
    // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
    alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
        AlarmManager.INTERVAL_HALF_HOUR, pIntent);
  }

详细解释参考https://guides.codepath.com/android/Starting-Background-Services#using-with-alarmmanager-for-periodic-tasks.

在 MyAlarmReceiver 的每个 onReceive 调用中,您都可以启动您的 intentservice。 您还应该阅读 https://developer.android.com/training/scheduling/alarms.html