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

时间:2016-06-26 02:28:33

标签: android push-notification background-service

目前,我有一个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());

我是否遗漏了任何实际创建通知的内容? (变量"标题","消息"和" id"已经设置)

1 个答案:

答案 0 :(得分:1)

使用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