繁体   English   中英

android与警报管理器的多个通知

[英]android multiple notifications with alarm manager

我有以下代码可用于与警报管理器设置多个通知:

接收者

public class NotificationPublisher extends BroadcastReceiver {

    public static String NOTIFICATION_ID = "notification-id";
    public static String NOTIFICATION = "notification";

    public void onReceive(Context context, Intent intent) {

        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = intent.getParcelableExtra(NOTIFICATION);
        notificationManager.notify(intent.getIntExtra(NOTIFICATION_ID, 0), notification);

    }
}

主要

 private void scheduleNotification(Notification notification, int delay) {


        Intent notificationIntent = new Intent(this, NotificationPublisher.class);
        notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, (int)System.currentTimeMillis());
        notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, (int)System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        long futureInMillis = System.currentTimeMillis() + delay;
        AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, futureInMillis, pendingIntent);
    }

    private Notification getNotification(String content) {

        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentTitle("Scheduled Notification");
        builder.setContentText(content);
        builder.setSmallIcon(R.drawable.ic_notification_appicon);
        builder.setDefaults(Notification.DEFAULT_SOUND);
        builder.setDefaults(Notification.DEFAULT_VIBRATE);
        builder.setAutoCancel(true);
        builder.setLights(Color.BLUE, 500, 500);
        return builder.getNotification();
    }

在创建我把这个代码:

scheduleNotification(getNotification("3 second delay"), 3000);
scheduleNotification(getNotification("5 second delay"), 5000);

这两个通知都会显示,但是同时显示(5秒后)我的错误在哪里?

好的,我找到了解决方案!

我改变:

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, (int)System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT)

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, (int)System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_ONE_SHOT);

您必须更改此行

notificationManager.notify(intent.getIntExtra(NOTIFICATION_ID, 0), notification);

用这个替换

notificationManager.notify(Unique_Integer_Number, notification);

唯一整数表示您必须设置永远不会重复的整数值。 例如0,1,2,3,4,5,.... !!!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM