2016-01-24 81 views
0

正在嘗試安排一個通知,其中包含所需的時間,如果在10秒後,我想要的時間是下面的代碼,但我不知道爲什麼它立即顯示通知,我是否做錯了什麼?或缺少什麼,請糾正我,如果我錯了任何地方,和現在用藍疊模擬器測試(內置版本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安排要廣播的IntentIntent可用於執行各種任務,如啓動ActivityService。據我所知,不可能使用Intent來顯示通知。

你應該看的是在Handler類中使用postDelayed()方法。例如:

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廣播。接下來,您將安排使用AlarmManager播放PendingIntent。當AlarmManager在10秒鐘後關閉PendingIntent時,您的BroadcastReceiver將收到廣播並呼叫notificationManager.notify()以顯示通知。這是相當迂迴的顯示通知的方式。