Reputation: 1591
For the life of me, I can't figure out why I can't set an exact time for an android notification. Been trying to figure this out for a few days, and still don't understand why.
Sometimes, it works on the exact same time from the time picker. But, sometimes it's 20 seconds, 34 seconds or even a full minute late. If someone could help me out, It'd be much appreciated because I don't know what else to do. I'm setting the time to the alarm manager from date milliseconds.
Broadcast Receiver:
public class AlertReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int code = intent.getIntExtra("code", 0);
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle("Task reminder!")
.setTicker(intent.getStringExtra("taskText"))
.setContentText(intent.getStringExtra("taskText"))
.setSmallIcon(R.drawable.ic_stat_name)
.setContentIntent(PendingIntent.getActivity(context, code, new Intent(context, MainActivity.class), 0))
.setAutoCancel(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build();
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.defaults = Notification.DEFAULT_SOUND;
notificationManager.notify(code, notification);
}
}
MainActivity:
int code = new Random().nextInt(1200) +
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), AlertReceiver.class);
intent.putExtra("taskText", taskInput.getText().toString());
intent.putExtra("code", code);
PendingIntent alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), code, intent, 0);
alarmMgr.set(AlarmManager.RTC, reminder, alarmIntent);
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
Getting my time from this:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.YEAR, datePicker.getYear());
cal.set(Calendar.MONTH, datePicker.getMonth());
cal.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
cal.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
cal.set(Calendar.MINUTE, timePicker.getCurrentMinute());
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Upvotes: 0
Views: 1706