從零開始學android -- notification通知

來源:互聯網
上載者:User

標籤: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通知

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.