歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android NotificationManager與Notification(通知欄)的使用

Android NotificationManager與Notification(通知欄)的使用

日期:2017/3/1 10:06:34   编辑:Linux編程

Android NotificationManager與Notification(通知欄)的使用:

有時候我們在後台運行程序,但是需要給用戶一個提示,在這個時候就需要使用提示信息了,即在提示欄顯示一個圖標或者是文字提醒用戶。

下面是實現的代碼:

  1. protected void showNotification(int id) {
  2. CharSequence from = "定位服務";
  3. CharSequence message = "正在運行";
  4. Intent intent = new Intent();
  5. PendingIntent contentIntent = PendingIntent.getActivity(this, 0,intent, 0);
  6. notif.icon = id;
  7. notif.setLatestEventInfo(this, from, message, contentIntent);
  8. NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  9. nm.notify(R.string.app_name, notif);
  10. }

其中ID表示的是圖片的ID,文字在這裡沒有添加,使用的時候按照添加圖標的方式可以自己添加!

這樣可以更改圖片。

下面這個是刪除提示的代碼:

  1. void delenot() {
  2. NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
  3. notificationManager.cancel(R.string.app_name);
  4. }

這樣我們添加的提示通知,可以清除掉,如果我們不想讓系統清除掉,那麼需要設置相關的屬性:

notif.flags

這個屬性可以設置為不清除或者是加入正在運行的列表。

Copyright © Linux教程網 All Rights Reserved