如何在android中的片段内创建特定日期和时间的通知

时间:2018-04-18 18:59:53

标签: android android-fragments push-notification

我的片段类包含以下代码:

Intent intent = new Intent(getActivity(), AlarmReceiver.class);

intent.putExtra("notificationId", notificationId);

intent.putExtra("todo",hello);

PendingIntent alarmIntent = PendingIntent.getBroadcast(getActivity(), 0,
            intent, PendingIntent.FLAG_CANCEL_CURRENT);

AlarmManager alarm = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);

Calendar startTime = Calendar.getInstance();

startTime.set(2018,3,18,20,30,0);

long alarmStartTime = startTime.getTimeInMillis();

alarm.set(AlarmManager.RTC_WAKEUP, alarmStartTime, alarmIntent);

AlarmReceiver.class包含如下内容。

public class AlarmReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

    // Get id & message from intent.
    int notificationId = intent.getIntExtra("notificationId", 0);
    String message = intent.getStringExtra("todo");

    // When notification is tapped, call MainActivity.
    Intent mainIntent = new Intent(context, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);

    NotificationManager myNotificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    // Prepare notification.
    Notification.Builder builder = new Notification.Builder(context);
    builder.setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle("It's Time!")
            .setContentText(message)
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setContentIntent(contentIntent)
            .setPriority(Notification.PRIORITY_MAX)
            .setDefaults(Notification.DEFAULT_ALL);

    // Notify
    myNotificationManager.notify(notificationId, builder.build());

}
}

在运行应用程序时,通知不会在2018年4月18日晚上8点30分创建

建议我进行一些更改,以便我可以很好地运行此应用程序。

1 个答案:

答案 0 :(得分:0)

尝试更改标记PendingIntent.FLAG_CANCEL_CURRENT

PendingIntent.FLAG_UPDATE_CURRENT

我希望这会有所帮助