I am looking for hours now how to do this exactly:
I want that every day (except weekends) a notification is sent at a time (let's say 18:00 (= 6pm)) except for when the app is open already. It's basically like the gmail app when you receive a mail. When the user clicks the notification it should disappear and should be brought to the MainActivity.
I have tried numerous things with the AlarmManager, but none have resulted in a notification showing up.
The code I tried, which I feel is pretty close to being correct, is following: In my MainActivity:
AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 18);
Intent intent = new Intent(this, NotificationService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
My NotificationService:
public class NotificationService extends IntentService {
public NotificationService() {
super("NotificationService");
}
@Override
@SuppressWarnings("deprecation")
protected void onHandleIntent(Intent intent) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "reminder", System.currentTimeMillis());
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent , 0);
notification.setLatestEventInfo(getApplicationContext(), "It's about time", "You should open the app now", contentIntent);
nm.notify(1, notification);
}
}
Notice I use deprecated stuff because this was even the only way a notification ever showed up while not working with the AlarmManager. If possible, please react with a solution that does not have the deprecated stuff in it, but with up to date stuff :P.
Many many many thanks in advance!!!
Kindest regards