Reputation:
I am developing an app where user wants to show the notification after his prescribed time Like 1 hour , 2 hour , 30 minutes , 40 minutes whatever he selects. but the problem I am facing is that notification appears at random time. sometime it appears after 1 hour as user selected, some time it appears after 30 minutes are so.
Code to trigger broadcast
long intervalSpan = timeInterVal * 60 * 1000; // timeInterVal is the value user enters in minutes
Calendar calendar = Calendar.getInstance();
Intent intentAlarm = new Intent(this, AlarmBroadCastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intentAlarm, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), intervalSpan, pendingIntent);
// also tried alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), intervalSpan, pendingIntent);
code to show notification inside broadcast
builder = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(content)
.setSound(mReminderSound ? alarmSound : null)
.setLights(mLed ? 0xff00ff00 : 0, 300, 100)
.setVibrate(mVibraion ? vibrate : new long[]{0L})
.setPriority(2)
.setStyle(new NotificationCompat.BigTextStyle().bigText(content))
.addAction(action)
.setSmallIcon(R.mipmap.ic_stat_call_white)
.setColor(Color.BLUE)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_launcher_logo))
.addAction(actionSnooze);
builder.setContentIntent(pendingIntent);
createNotification(contextl, builder);
}
private void createNotification(Context context, NotificationCompat.Builder builder) {
mNotificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.notify(Constants.NOTIFICATION_ID,
builder.build());
}
Please tell me what I am doing wrong.
Upvotes: 1
Views: 93
Reputation: 451
You can use JobScheduler for repeating task.
ComponentName serviceComponent = new ComponentName(context, TestJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(15, serviceComponent);
builder.setPeriodic(20*60*1000); // this will repeat after every 20 minutes
builder.setPersisted(true);
JobScheduler jobScheduler = (JobScheduler)context.getApplicationContext().getSystemService(JOB_SCHEDULER_SERVICE);
if (jobScheduler != null) {
jobScheduler.schedule(builder.build());
}
TestJobService.class
public class TestJobService extends JobService { @Override public boolean onStartJob(JobParameters params) { // create notification here return false; } @Override public boolean onStopJob(JobParameters params) { return true; } }
Upvotes: 2