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

Android Notification 與 NotificationManager 詳解

編輯:關於 Android 程式設計

在 Android 中,狀態列提醒(Notification)是一種不會打斷使用者當前操作的通知方式。相比於彈出式、會搶走焦點的 AlertDialog,Notification 更為友善——想像使用者正在玩遊戲時收到一條簡訊,若用 AlertDialog 強制打斷,體驗必然糟糕;而用 Notification,使用者完全可以打完遊戲再從容查看。因此在開發中,應依實際需求選擇合適的通知形式。

步驟一:加入佈局物件

<Button
    android:id="@+id/showButton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="showNotification" />
<Button
    android:id="@+id/cancelButton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="cancelNotification" />

步驟二:實作 MainActivity

讓 Activity 實作 OnClickListener 介面,即可用簡潔的方式為多個按鈕綁定點擊事件。核心元件是 NotificationManager(負責發送與取消通知)與 Notification(承載通知內容):

public class MainActivity extends Activity implements OnClickListener {
    private Context mContext = this;
    private Button showbtn, calclebtn;
    private Notification noti;
    private NotificationManager notiManger;
    private static int NOTIFICATION_ID = 0x0001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setUpViews();
    }
    private void setUpViews() {
        showbtn = (Button) findViewById(R.id.showButton);
        calclebtn = (Button) findViewById(R.id.cancelButton);
        noti = new Notification(R.drawable.ic_launcher, "this is a notification", System.currentTimeMillis());
        noti.defaults = Notification.DEFAULT_SOUND;   // 使用預設提示音
        noti.defaults |= Notification.DEFAULT_VIBRATE; // 加上震動
        notiManger = (NotificationManager) this.getSystemService(mContext.NOTIFICATION_SERVICE);
        showbtn.setOnClickListener(this);
        calclebtn.setOnClickListener(this);
    }
    // 按鈕點擊回應
    @Override
    public void onClick(View v) {
        if (v == showbtn) {
            Intent intent = new Intent(this.getApplicationContext(), this.getClass());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
            // setLatestEventInfo(上下文, 標題, 內容, PendingIntent)
            noti.setLatestEventInfo(this, "10086", "你從此以後免除所有話費", contentIntent);
            notiManger.notify(NOTIFICATION_ID, noti); // 發送通知
        } else if (v == calclebtn) {
            notiManger.cancel(NOTIFICATION_ID); // 取消通知
        }
    }
}

這裡的關鍵概念是 PendingIntent:它封裝了一個「未來要執行的意圖」,當使用者點擊通知時,系統便會執行它、跳轉到指定頁面。透過 notify() 發送、cancel() 取消,就能完整掌握通知的顯示與消失時機。

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