標籤:put 位置 http 應用程式 build 預設 nbsp service 意圖
看看效果
布局什麼的太簡單了我就不放在上面了給你們看核心的代碼就行了 裡面的 int notificationID = 1;
//設定點擊通知後的意圖 Intent intent = new Intent(this,NotificationView.class); intent.putExtra("notificationID",notificationID); //塞入pendingIntent 參數解釋:1.上下文也就是context 2.請求碼(用於意圖的請求碼) 3.意圖(用來啟動目標活動的意圖) 4.標誌(活動啟動時使用的標誌) PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT); //擷取系統的notification管理服務 NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); //現在官方推薦用builder的方式構建Notification,原來是new的方式已經淘汰了。 Notification.Builder builder = new Notification.Builder(this); //收到通知時最頂部顯示的資訊 builder.setSmallIcon(R.mipmap.ic_launcher); builder.setTicker("Reminder:Meeting starts in 5 minutes"); builder.setWhen(System.currentTimeMillis()); //下拉頂部看到的詳細通知資訊 表徵圖通用的 builder.setContentTitle("System Alarm"); //設定標題 builder.setContentText("Meeting with customer at 3pm.."); //設定內容 //設定通知被點擊後的意圖處理也就是開啟某個activity //至於為什麼要用pendingIntent ,因為PendingIntent對象可以代表應用程式協助您在後面的某個時候執行一個動作,而“不用考慮應用程式是否正在運行” builder.setContentIntent(pendingIntent); builder.setDefaults(Notification.DEFAULT_SOUND); //設定預設的聲音和震動 //當然你也可以自訂設定震動// builder.setVibrate(new long[]{100,250,100,500}); //設定震動 builder.setAutoCancel(true);//設定點擊後自動消失也就是取消顯示 true:點擊後消失;false:點擊後不消失;預設是false Notification notif = builder.build(); //構建 這裡注意build方法最低支援minSdkVersion 16 manager.notify(notificationID,notif); //notification管理服務發送你所構建的通知 此時你會收到通知
注意裡面的builder.setAutoCancel(true); 如果你不想程式自動幫你點擊後關閉,而是自己用代碼在另一個位置自己去關閉,那麼你可以不寫這句代碼,也可以設定成false,然後關閉代碼可以這麼寫
//擷取服務 NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); nm.cancel(getIntent().getIntExtra("notificationID",1)); //關閉顯示notificationID為1的通知
切記關閉id與你通知一致的id。好好學習,天天向上,就這麼多了。
學習記錄,如果有錯請指出,謝謝!
從零開始學android -- notification通知