Search code examples
androidnotificationsalarmmanager

android notification not being sent


I am trying to send a notification to the user on the day they set on the datePicker.

A notification isn't being sent and I don't know why.

The variable context is defined in the onReceive as the context that is passed.

public void setAlarm() {
        int year = datePicker.getYear();
        int month = datePicker.getMonth();
        int day = datePicker.getDayOfMonth();

        Calendar c = Calendar.getInstance();
        c.set(year, month, day);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);

        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(context, NotifyReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        am.set(AlarmManager.RTC, c.getTimeInMillis(), pendingIntent);

        Toast.makeText(context, "Set reminder for: " + (month+1) + "/" + day + "/" + year, Toast.LENGTH_LONG).show();

    }

The broadcast receiver:

public class NotifyReceiver extends BroadcastReceiver {

    private static final int NOTIFICATION = 12368327;

    private NotificationManager mNM;

    private Context context;

    @Override
    public void onReceive(Context ctx, Intent intent) {
        mNM = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        context = ctx;
        showNotification();
    }

    private void showNotification() {

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);

        Notification noti = new Notification.Builder(context)
                .setContentTitle("Title")
                .setContentText("Text").setSmallIcon(R.drawable.ic_launcher)
                .setContentIntent(contentIntent).build();

        // Clear the notification when it is pressed
        noti.flags |= Notification.FLAG_AUTO_CANCEL;

        // Send the notification to the system.
        mNM.notify(NOTIFICATION, noti);
    }
}

I also get the toast when the method is called meaning the alarm is being set.


Solution

  • Try this line

    please set your AlarmManager

    am .setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, 1000,pendingIntent_for_every_second);
    

    Thanks