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

Android Notification 基本用法:建立並發送狀態列通知

編輯:關於 Android 程式設計

以下範例示範如何用 Handler 每五秒送出一則通知,並透過不同的 id 區分不同則通知。

package com.example.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.os.Handler;

public class MainActivity extends Activity {
 private Handler handler = new Handler();
 private int mId = 0;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 handler.post(runnable);
 }

 private Runnable runnable = new Runnable() {
 @Override
 public void run() {
 if(mId < 3) {
 sendNotification(mId);
 mId++;
 }
 handler.postDelayed(runnable, 5000);
 }
 };

 /**
 * 依不同的 id 發送不同內容的通知
 *
 * @param mId
 */
 @SuppressWarnings("deprecation")
 protected void sendNotification(int mId) {
 NotificationManager notificationManager =
 (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

 Notification noti = new Notification(R.drawable.ic_launcher,
 "狀態欄顯示滾輪信息", System.currentTimeMillis());
 noti.defaults |= Notification.DEFAULT_VIBRATE;
 // noti.vibrate = null;
 noti.defaults |= Notification.DEFAULT_SOUND;
 // noti.sound = null;
 noti.flags |= Notification.FLAG_AUTO_CANCEL;

 Intent intent = new Intent(MainActivity.this, ResultActivity.class);
 intent.putExtra("fromTag", "傳遞數據");
 PendingIntent pendingIntent = PendingIntent.getActivity(
 MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

 noti.setLatestEventInfo(MainActivity.this,
 "通知欄標題" + mId, "通知欄信息詳情" + mId, pendingIntent);

 notificationManager.notify(mId, noti);
 }

 @Override
 protected void onDestroy() {
 handler.removeCallbacks(runnable);
 super.onDestroy();
 }
}

幾個重點說明:

· NotificationManager 是發送通知的入口,透過 getSystemService 取得。

· defaults 用位元 OR 累加效果,這裡同時指定了震動與提示音;若要自訂,可改用 noti.vibrate 與 noti.sound 明確指定。

· FLAG_AUTO_CANCEL 讓使用者點掉通知後它會自動消失。

· PendingIntent 決定點擊通知後要跳到哪裡;FLAG_UPDATE_CURRENT 表示若已存在相同的 PendingIntent 就更新其 extras。

· 最後務必在 onDestroy 中移除 Handler 的 callback,否則 Activity 銷毀後仍會持續被觸發,造成記憶體洩漏。

需要提醒的是,範例中的 Notification 建構子與 setLatestEventInfo() 都已在新版 Android 被棄用。若要在 Android 8.0(API 26)以上正常顯示通知,必須改用 Notification.Builder、建立 NotificationChannel,並在 AndroidManifest.xml 宣告 POST_NOTIFICATIONS 權限(API 33 起需要執行期授權)。本範例可作為理解通知組成元素的入門參考。

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