I want to build a water reminder app. This app should send notifications every time you are supposed to drink water, according to some calculations that the app does beforehand. I know how to use an AlarmManager
to schedule one-time alarms and repeated alarms. What I haven't figured out, after searching quite a lot, is how I am going to use an AlarmManager
to schedule a specific number of alarms (say 6) every day, stop at a specific time during the day (say 10.00pm) and start send notifications the next day at a specific time (say 07.00am). All of this should happen without the user having to open the app. How do I do this? Here's my code:
Part of MainActivity:
Long alertTime = nextAlarm.getTimeInMillis();
Intent alertIntent = new Intent(this, AlertReceiver.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime,
PendingIntent.getBroadcast(this, 1, alertIntent,
PendingIntent.FLAG_UPDATE_CURRENT));
AlertReceiver:
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
public class AlertReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent
intent) {
createNotification(context, "Hydrate", "Time to drink water", "Alert");
}
public void createNotification(Context context, String msg, String msgText, String msgAlert) {
PendingIntent notificationIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_drop_24dp)
.setContentTitle(msg)
.setContentText(msgText)
.setTicker(msgAlert);
notificationBuilder.setContentIntent(notificationIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_ALL);
notificationBuilder.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());
}
}
Thanks for the help!