Vaibhav Aggarwal
Vaibhav Aggarwal

Reputation: 1411

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.

Upvotes: 0

Views: 92

Answers (2)

Dehan Wjiesekara
Dehan Wjiesekara

Reputation: 3182

You should pass "month" parameter by reducing one.

e.g if your month is October then you should pass 9 instead of 10

use

c.set(year, month-1, day);

instead of

c.set(year, month, day);

no need to use set repeating.

Upvotes: 0

Md Abdul Gafur
Md Abdul Gafur

Reputation: 6201

Try this line

please set your AlarmManager

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

Thanks

Upvotes: 1

Related Questions