Reputation: 297
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. 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.
Also, I want to make sure that I'm sending notifications the right way. In IntentService.onHandleIntent(), I have this for sending the notification.
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)
Upvotes: 0
Views: 691
Reputation: 326
Use AlarmManager for repeated tasks.
// 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.
In every onReceive call of MyAlarmReceiver you can start your intentservice. You should also read https://developer.android.com/training/scheduling/alarms.html
Upvotes: 1