Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中建立通知欄 Notification 的程式碼實例

編輯:關於 Android 程式設計

以下示範如何在 Android 中建立通知欄的 Notification:

 ///// 第一步:獲取NotificationManager NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); ///// 第二步:定義Notification Intent intent = new Intent(this, OtherActivity.class); //PendingIntent是待執行的Intent PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); Notification notification = new Notification.Builder(this) .setContentTitle("title") .setContentText("text") .setSmallIcon(R.drawable.ic_launcher).setContentIntent(pi) .build(); notification.flags = Notification.FLAG_NO_CLEAR; /////第三步:啟動通知欄,第一個參數是一個通知的唯一標識 nm.notify(0, notification); //關閉通知 //nm.cancel(0);

整個流程分為三步:先取得 NotificationManager,再用 Notification.Builder 搭配 PendingIntent 建立通知物件,最後呼叫 notify 發出通知;若要關閉,則呼叫 cancel 並傳入相同的識別碼即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved