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

Notification 通知欄訊息實作(含自訂版面)

編輯:關於 Android 開發

一個很典型的場景:使用者開啟 Activity 後按下 Home 鍵,此時流程會走 onPause() → onStop(),介面不可見。我們就在這個時機送一則 Notification 到通知欄;使用者點擊它之後,Activity 透過 onRestart() → onStart() → onResume() 重新回到前景。

完整程式碼

package com.zzw.testnotification;

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.support.v4.app.NotificationCompat.Builder;
import android.util.Log;
import android.widget.RemoteViews;

public class MainActivity extends Activity {

    private static final String TAG = "---->";
    private final int NOTIFICATION_ID = 0xa01;
    private final int REQUEST_CODE = 0xb01;

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate");
    }

    @Override protected void onResume()   { Log.d(TAG, "onResume");   super.onResume(); }
    @Override protected void onDestroy()  { Log.d(TAG, "onDestroy");  super.onDestroy(); }
    @Override protected void onPause()    { Log.d(TAG, "onPause");    super.onPause(); }
    @Override protected void onRestart()  { Log.d(TAG, "onRestart");  super.onRestart(); }
    @Override protected void onStart()    { Log.d(TAG, "onStart");    super.onStart(); }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
        sendNotification(this, NOTIFICATION_ID, "這是標題", "這是內容");
    }

    // 可當作發送通知的通用模板
    private void sendNotification(Context context, int notification_ID, String title, String content) {
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        // 使用系統預設版面
        Builder builder = new Builder(context);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setContentTitle(title);
        builder.setContentText(content);

        Notification notification = builder.build();

        /* 若要使用自訂版面,改用 RemoteViews:
        RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification);
        contentView.setImageViewResource(R.id.imageView, R.drawable.ic_launcher);
        contentView.setTextViewText(R.id.title, "土耳其和IS的秘密");
        contentView.setTextViewText(R.id.text, "土耳其拒絕向俄羅斯道歉,懷疑有IS撐腰");
        notification.contentView = contentView;
        */

        // 提示音 + 震動 + 呼吸燈
        // 注意:前兩項幾乎所有 Android 手機都支援,呼吸燈則取決於各家的硬體設計
        notification.defaults = Notification.DEFAULT_SOUND
                | Notification.DEFAULT_VIBRATE
                | Notification.DEFAULT_LIGHTS;

        // 點擊後自動消失
        notification.flags = Notification.FLAG_AUTO_CANCEL;

        // 通知時間
        notification.when = System.currentTimeMillis();

        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(context, REQUEST_CODE, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        notification.contentIntent = pi;

        notificationManager.notify(notification_ID, notification);
    }

    // 可當作清除通知的通用模板
    private void deleteNotification(int id) {
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancel(id);
    }
}

關鍵:啟動模式

Android Activity 預設是 standard 模式,每次啟動都會 new 一個新實例。若不改設定,每次點通知回來都會重新走一次 onCreate(),畫面上的計數 therefore 一直遞增。要沿用原本的 Activity,需在 AndroidManifest.xml 中把啟動模式改為 singleTop:

<activity android:name=".MainActivity"
    android:label="@string/app_name"
    android:launchMode="singleTop" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

自訂版面:notification.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/text"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/imageView"
        android:layout_marginLeft="18dp"
        android:layout_toRightOf="@+id/imageView"
        android:gravity="center_vertical"
        android:singleLine="true"
        android:text="TextView" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageView"
        android:layout_alignLeft="@+id/title"
        android:gravity="center_vertical"
        android:singleLine="true"
        android:text="TextView" />

</RelativeLayout>

震動權限

部分 SDK 版本需要額外宣告震動權限,否則 DEFAULT_VIBRATE 不會生效:

<uses-permission android:name="android.permission.VIBRATE"/>

版本提醒

Android 8.0(API 26)起,通知必須綁定 NotificationChannel,否則完全不會顯示;而自訂 RemoteViews 通知版面在 Android 12 之後也已被限制,只允許使用有限的樣式屬性。上述寫法適合作為理解通知機制的入門範例,新專案建議改用 NotificationCompat.Builder 搭配 setCustomContentView 並建立 channel。

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