本地通知立即触发

时间:2017-03-06 10:37:00

标签: java android

我使用以下代码在android中触发本地通知。

            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
            notificationIntent.addCategory("android.intent.category.DEFAULT");

            PendingIntent broadcast = PendingIntent.getBroadcast(NewPaymentReminder.this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.MONTH, Integer.parseInt(Month_only));
            cal.set(Calendar.YEAR, Integer.parseInt(Year_only));
            cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(Date_only));

            cal.set(Calendar.HOUR_OF_DAY, hour);
            cal.set(Calendar.MINUTE, min);
            //  cal.set(Calendar.SECOND, secs);
            cal.set(Calendar.AM_PM, Calendar.PM);

            System.out.println("Calender - Get time in Milliseconds" + cal.getTimeInMillis());

            alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), broadcast);

RECEIVER CLASS:

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent notificationIntent = new Intent(context, MyPaymentReminder.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(MyPaymentReminder.class);
        stackBuilder.addNextIntent(notificationIntent);

        PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

        Notification notification = builder.setContentTitle("Payment Reminder")
                .setContentText("New Notification")
                .setTicker("New Message Alert!")
                .setSmallIcon(R.drawable.logo)
                .setContentIntent(pendingIntent).build();

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notification);
    }
}

我已经在Manifest注册了我的接收器,并且我收到了Receiver类中的数据。但我的问题是我想在特定的日期和时间触发通知,但它立即触发!任何帮助将非常感谢朋友!

1 个答案:

答案 0 :(得分:0)

检查是否

System.out.println("Calender - Get time in Milliseconds" + cal.getTimeInMillis());

是未来的打印时间。

如果你将ApiLevel定位在19以上,你也应该使用alarmManager.setExact:https://developer.android.com/reference/android/app/AlarmManager.html#setExact(int,%20long,%20android.app.PendingIntent)

相关问题