[英]Make Background Service run on startup as well as every minute
Currently, I have a IntentService that checks a php server for new notifications intended for the user, and a BroadcastReceiver that listens for BOOT_COMPLETED. 当前,我有一个IntentService,它检查php服务器上是否有针对该用户的新通知;以及一个BroadcastReceiver,它侦听BOOT_COMPLETED。 What I wanna know is how do I combine to two to not only make the IntentService run on startup, but also make the IntentService run every minute from that point. 我想知道的是如何将两者结合在一起,不仅使IntentService在启动时运行,而且使IntentService从此开始每分钟运行一次。
Also, I want to make sure that I'm sending notifications the right way. 另外,我想确保以正确的方式发送通知。 In IntentService.onHandleIntent(), I have this for sending the notification. 在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());
Am I missing anything for this to actually create the notification? 我是否为此实际创建通知而缺少任何信息? (The variables "title", "message", and "id" are already set) (变量“ title”,“ message”和“ id”已设置)
Use AlarmManager for repeated tasks. 使用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);
}
For Detailed explanation refer https://guides.codepath.com/android/Starting-Background-Services#using-with-alarmmanager-for-periodic-tasks . 有关详细说明,请参阅https://guides.codepath.com/android/Starting-Background-Services#using-with-alarmmanager-for-periodic-tasks 。
In every onReceive call of MyAlarmReceiver you can start your intentservice. 在MyAlarmReceiver的每个onReceive调用中,您都可以启动intentservice。 You should also read https://developer.android.com/training/scheduling/alarms.html 您还应该阅读https://developer.android.com/training/scheduling/alarms.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.