Search code examples
androidtimenotificationsbroadcastreceiveralarmmanager

Android - Create Repeating Notification At Set Time


I have looked through a ton of documentation and stackoverflow questions on how to set a repeating notification set to a certain time but can not get any of them to work. Here is what I have right now.

The method I set up the AlarmManager in:

//set alarm method
private void setAlarm() {
    if(enableCheckBox.isChecked()) {
        //save time / title / message
        mTinyDB.putInt(Constants.SAVED_HOUR, timePicker.getCurrentHour());
        mTinyDB.putInt(Constants.SAVED_MINUTE, timePicker.getCurrentMinute());
        mTinyDB.putString(Constants.SAVED_TITLE, titleEditText.getText().toString().trim());
        mTinyDB.putString(Constants.SAVED_MESSAGE, messageEditText.getText().toString().trim());
        mTinyDB.putBoolean(Constants.SAVED_NOTIFICATION_ENABLED, enableCheckBox.isChecked());

        //create repeating notification
        Intent intent = new Intent(NotificationActivity.this, Notify.class);
        AlarmManager manager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getService(this,
                0, intent, 0);
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, mTinyDB.getInt(Constants.SAVED_HOUR, 0));
        cal.set(Calendar.MINUTE,  mTinyDB.getInt(Constants.SAVED_MINUTE, 0));
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        manager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 24 * 60 * 60 * 1000, pendingIntent);
    }
}

The Notify class which extends BoradcastReceiver:

public class Notify extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    TinyDB mTinyDB = new TinyDB(context);
    Notification builder = new Notification.Builder(context)
            .setContentTitle(mTinyDB.getString(Constants.SAVED_TITLE))
            .setContentText(mTinyDB.getString(Constants.SAVED_MESSAGE))
            .setSmallIcon(R.drawable.ic_action_check)
            .setContentIntent(pIntent)
            .build();
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1, builder);
}

}

Am I doing this completely wrong? I can't get anything to come up (at least at the set time). Help or guidance is appreciated :)


Solution

  • You're using PendingIntent.getService, but your intent is not for a service. For a BroadcastReceiver, you should be using PendingIntent.getBroadcast.

    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);