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

Android 通知(Notification)詳解:從發送到點擊跳轉

編輯:關於 Android 程式設計

最近專案裡用到了 Android 的通知機制,趁機會透過一個完整範例把整個流程走一遍。

發送一則通知其實很簡單

核心只有三件事:建立 PendingIntent 決定點擊後要做什麼、用 NotificationCompat.Builder 組出通知內容、最後交給 NotificationManager 發出。

private void showNotification(int id, String title, String data) {
    Intent broadcastIntent = new Intent(this, NotificationReceiver.class);
    // 用一個廣播接收者來承接點擊後的行為
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            this, id, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
    mBuilder.setContentTitle(title)                    // 通知標題
            .setContentText(data)                      // 通知內容
            .setContentIntent(pendingIntent)           // 點擊通知後的 action
            .setSmallIcon(R.drawable.pushsmall)        // 狀態列小圖示
            .setLargeIcon(BitmapFactory.decodeResource( // 通知區大圖示
                    getResources(), R.drawable.ic_launcher))
            .setAutoCancel(true);                      // 點擊後自動消失

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(id, mBuilder.build());
}

接收點擊:NotificationReceiver

這裡有個實務上很重要的判斷:點通知時,App 行程可能還活著,也可能已經被系統回收。兩種情況的跳轉方式完全不同——前者直接開啟目標 Activity,後者則必須先拉起啟動 Activity 建立返回堆疊,否則使用者按返回鍵會直接回到桌面。

public class NotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (isAppAlive(context, "com.bandeng.temp")) {
            // 行程存活:直接前進目標頁
            Intent startIntent = new Intent(context, PushActivity.class);
            startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(startIntent);
        } else {
            // 行程已結束:先走啟動頁,再疊上目標頁,保住返回堆疊
            Intent launchIntent = context.getPackageManager()
                    .getLaunchIntentForPackage("com.bandeng.temp");
            launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            Intent detailIntent = new Intent(context, PushActivity.class);
            Intent[] intents = {launchIntent, detailIntent};
            context.startActivities(intents);
        }
    }

    private boolean isAppAlive(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(packageName)
                    && info.baseActivity.getPackageName().equals(packageName)) {
                return true;
            }
        }
        return false;
    }
}

實際效果

一個容易忽略的坑:Android 5.0 之後的小圖示

從 Android 5.0 開始,setSmallIcon() 指定的圖示如果不是「背景透明」的素材,系統會把它整個渲染成白色方塊,看起來就是一個小白點。上面範例之所以正常,是因為 pushsmall 的背景是透明的。

如果直接把大圖示塞給小圖示位置:

mBuilder.setSmallIcon(R.drawable.ic_launcher)

就會看到這個問題:

國產手機上通常看不出差別,因為不少廠商修改過系統實作,會直接以大圖示取代小圖示。但為了在原生系統上也能正常顯示,還是應該準備一張「單色、背景透明」的小圖示給 setSmallIcon(),大圖示則另外用 setLargeIcon() 提供。

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