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

Android Notification 的三種典型寫法與相容處理

編輯:關於 Android 程式設計

收到新訊息時,即使我們沒有打開 App,手機最上方的狀態列也會出現一個小圖示提醒。這個效果靠的就是 Notification。本文整理了三種不同時期的 Notification 寫法,並說明它們各自適用的 Android 版本。

先看實際效果:

核心觀念

要在 Android 上發出通知,第一步永遠是取得系統的 NotificationManager,它本身就是一個系統 Service。另外還需要 PendingIntent:它和一般 Intent 很像,差別在於「不是立刻執行」,而是先包好,等使用者點擊通知時才觸發,用來決定點下去要跳去哪個 Activity。

主要程式碼

 package net.loonggg.notification; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.RemoteViews; public class MainActivity extends Activity { private static final int NOTIFICATION_FLAG = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void notificationMethod(View view) { // 在Android進行通知處理,首先需要重系統哪裡獲得通知管理器NotificationManager,它是一個系統Service。 NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); switch (view.getId()) { // 默認通知 case R.id.btn1: // 創建一個PendingIntent,和Intent類似,不同的是由於不是馬上調用,需要在下拉狀態條出發的activity,所以采用的是PendingIntent,即點擊Notification跳轉啟動到哪個Activity PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); // 下面需兼容Android 2.x版本是的處理方式 // Notification notify1 = new Notification(R.drawable.message, // "TickerText:" + "您有新短消息,請注意查收!", System.currentTimeMillis()); Notification notify1 = new Notification(); notify1.icon = R.drawable.message; notify1.tickerText = "TickerText:您有新短消息,請注意查收!"; notify1.when = System.currentTimeMillis(); notify1.setLatestEventInfo(this, "Notification Title", "This is the notification message", pendingIntent); notify1.number = 1; notify1.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明當通知被用戶點擊時,通知將被清除。 // 通過通知管理器來發起通知。如果id不同,則每click,在statu那裡增加一個提示 manager.notify(NOTIFICATION_FLAG, notify1); break; // 默認通知 API11及之後可用 case R.id.btn2: PendingIntent pendingIntent2 = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); // 通過Notification.Builder來創建通知,注意API Level // API11之後才支持 Notification notify2 = new Notification.Builder(this) .setSmallIcon(R.drawable.message) // 設置狀態欄中的小圖片,尺寸一般建議在24×24,這個圖片同樣也是在下拉狀態欄中所顯示,如果在那裡需要更換更大的圖片,可以使用setLargeIcon(Bitmap // icon) .setTicker("TickerText:" + "您有新短消息,請注意查收!")// 設置在status // bar上顯示的提示文字 .setContentTitle("Notification Title")// 設置在下拉status // bar後Activity,本例子中的NotififyMessage的TextView中顯示的標題 .setContentText("This is the notification message")// TextView中顯示的詳細內容 .setContentIntent(pendingIntent2) // 關聯PendingIntent .setNumber(1) // 在TextView的右方顯示的數字,可放大圖片看,在最右側。這個number同時也起到一個序列號的左右,如果多個觸發多個通知(同一ID),可以指定顯示哪一個。 .getNotification(); // 需要注意build()是在API level // 16及之後增加的,在API11中可以使用getNotificatin()來代替 notify2.flags |= Notification.FLAG_AUTO_CANCEL; manager.notify(NOTIFICATION_FLAG, notify2); break; // 默認通知 API16及之後可用 case R.id.btn3: PendingIntent pendingIntent3 = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); // 通過Notification.Builder來創建通知,注意API Level // API16之後才支持 Notification notify3 = new Notification.Builder(this) .setSmallIcon(R.drawable.message) .setTicker("TickerText:" + "您有新短消息,請注意查收!") .setContentTitle("Notification Title") .setContentText("This is the notification message") .setContentIntent(pendingIntent3).setNumber(1).build(); // 需要注意build()是在API // level16及之後增加的,API11可以使用getNotificatin()來替代 notify3.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明當通知被用戶點擊時,通知將被清除。 manager.notify(NOTIFICATION_FLAG, notify3);// 步驟4:通過通知管理器來發起通知。如果id不同,則每click,在status哪裡增加一個提示 break; // 自定義通知 case R.id.btn4: // Notification myNotify = new Notification(R.drawable.message, // "自定義通知:您有新短信息了,請注意查收!", System.currentTimeMillis()); Notification myNotify = new Notification(); myNotify.icon = R.drawable.message; myNotify.tickerText = "TickerText:您有新短消息,請注意查收!"; myNotify.when = System.currentTimeMillis(); myNotify.flags = Notification.FLAG_NO_CLEAR;// 不能夠自動清除 RemoteViews rv = new RemoteViews(getPackageName(), R.layout.my_notification); rv.setTextViewText(R.id.text_content, "hello wrold!"); myNotify.contentView = rv; Intent intent = new Intent(Intent.ACTION_MAIN); PendingIntent contentIntent = PendingIntent.getActivity(this, 1, intent, 1); myNotify.contentIntent = contentIntent; manager.notify(NOTIFICATION_FLAG, myNotify); break; case R.id.btn5: // 清除id為NOTIFICATION_FLAG的通知 manager.cancel(NOTIFICATION_FLAG); // 清除所有的通知 // manager.cancelAll(); break; default: break; } } }

主版面配置

五顆按鈕分別對應五種情境,其中前三種是系統預設樣式在不同 API Level 下的寫法,第四種是自訂版面,第五種負責清除通知。

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <Button android:id="@+id/btn1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="notificationMethod" android:text="默認通知(已被拋棄,但是通用)" /> <Button android:id="@+id/btn2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="notificationMethod" android:text="默認通知(API11之後可用)" /> <Button android:id="@+id/btn3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="notificationMethod" android:text="默認通知(API16之後可用)" /> <Button android:id="@+id/btn4" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="notificationMethod" android:text="自定義通知" /> <Button android:id="@+id/btn5" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="notificationMethod" android:text="清除通知" /> </LinearLayout> 

自訂通知的版面檔

自訂樣式時,通知內容其實是塞進一個 RemoteViews 裡,因此版面檔能用的控制項相當有限,這一點後面會再談到。

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#ffffff" android:orientation="vertical" > <TextView android:id="@+id/text_content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" /> </LinearLayout> 

三種預設寫法裡,setLatestEventInfo 這條路已被官方淘汰,但為了照顧舊版本仍得留著;新專案建議直接採用 Notification.Builder,並搭配 NotificationCompat 做向下相容。

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