立即显示通知

时间:2016-01-24 11:42:12

标签: android

我正在尝试按照所需的时间安排通知,如果在10秒后我不知道为什么它会立即显示通知,我会在下面的代码中使用以下代码,我做错了什么?或丢失任何东西,如果我在任何地方出错,请纠正我,并使用BlueStacks Emulator进行测试(内置版本4.4.2 Api 19)

notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);

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


PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);

alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), broadcast);
// why its showing up instantly insted of after 10 seconds 

//alarmManager.setExact(AlarmManager.RTC_WAKEUP,20,broadcast);


Intent intent = new Intent(this , MainActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent , PendingIntent.FLAG_UPDATE_CURRENT);

Intent switchIntent = new Intent(this, switchButtonListener.class);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, switchIntent, 0);

notification.setSmallIcon(R.drawable.ok);
notification.setWhen(20);
notification.setTicker("you've got a meesage");
notification.setContentTitle("new message");
notification.setContentText("wanna take a ride?");

//   notification.setContentIntent(pendingIntent);

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(uniqueID, notification.build());

1 个答案:

答案 0 :(得分:0)

  

立即显示通知

当您在最后一行中致电notificationManager.notify()时,会立即显示通知。

我认为你想使用AlarmManager来显示通知,而你却不太了解它的作用。 AlarmManager用于安排Intent广播。 Intent可用于执行各种任务,例如启动ActivityService。据我所知,无法使用Intent来显示通知。

您应该注意的是在postDelayed()课程中使用Handler方法。例如:

handler = new Handler();

final Runnable r = new Runnable() {
    public void run() {
        // Create your notification using NotificationCompat.Builder
        // and call notificationManager.notify()
    }
};

handler.postDelayed(r, /*time to delay for in ms*/);

编辑:如果您确实想要使用AlarmManager并通过广播来显示通知,则需要延长BroadcastReceiver并让它监听您的PendingIntent广播。接下来,您将使用PendingIntent安排AlarmManager广播。当AlarmManager在10秒后触发PendingIntent时,您的BroadcastReceiver将收到广播并致电notificationManager.notify()以显示通知。这是一种显示通知的迂回方式。