2016-01-24 2 views
0

Я пытаюсь запланировать уведомление с требуемым временем и не ниже кода желаемого времени, если через 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()); 

ответ

0

уведомление появляется мгновенно

Когда вы звоните notificationManager.notify() в вашей последней строке он немедленно отображает уведомление.

Я предполагаю, что вы хотели использовать AlarmManager для отображения уведомления, и вы не совсем понимаете, что он делает. В поле AlarmManager используется расписание Intent. Intent может использоваться для выполнения множества задач, таких как запуск Activity или Service. Насколько я знаю, для отображения уведомления невозможно использовать 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*/); 

Edit: Если вы действительно хотите использовать AlarmManager и трансляции для отображения уведомлений, вам нужно будет расширить BroadcastReceiver и иметь его слушать для PendingIntent вещания. Затем вы планируете использовать PendingIntent, используя AlarmManager. Когда AlarmManager погаснет PendingIntent через 10 секунд, ваш BroadcastReceiver получит широковещательную передачу и вызовет notificationManager.notify(), чтобы отобразить уведомление. Это довольно крутой способ отображения уведомлений.

Смежные вопросы