Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Notification 通知分類與實現方式全面總結

編輯:Android 開發實例

通知(Notification)是 Android 應用與用戶溝通的重要橋樑。本文把通知按形態分類,並給出各類的完整實現代碼與實戰要點。

一、普通通知

構成部分依次為:

  1. 內容標題
  2. 大圖標
  3. 內容
  4. 內容附加信息
  5. 小圖標
  6. 時間

二、大布局通知

圖1

大布局通知是 Android 4.1 之後才引入的能力。它與普通通知僅在第 7 部分(內容區)有差異,其餘完全一致。值得注意的是,大布局只有在通知位於列表最頂部時才會完整展開,其他位置仍顯示小布局;用戶也可以用手指將其下拉展開。

圖2

大布局共有三種類型:圖 1 是 NotificationCompat.InboxStyle(收件箱樣式),圖 2 左側是 NotificationCompat.BigTextStyle(大文本樣式),圖 2 右側是 NotificationCompat.BigPictureStyle(大圖樣式)。

三、自定義布局通知

除了系統提供的樣式,我們還可以完全自定義通知界面。如下圖所示的音樂播放器控制通知:

圖3

如何創建一條通知


  1. 實例化一個 NotificationCompat.Builder 對象
  2. 調用 builder 的相關方法進行各項設置
  3. 調用 builder.build() 得到 Notification 對象
  4. 實例化一個 NotificationManager 對象
  5. 調用 manager.notify() 發送

注意:並非所有選項都必須設置,但有三項是強制要求:

  • 小圖標,通過 setSmallIcon() 設置
  • 內容標題,通過 setContentTitle() 設置
  • 內容,通過 setContentText() 設置

示例代碼


示例程序截圖:

0. 初始化部分

public class MainActivity extends Activity implements OnClickListener {

    private static final int NOTIFICATION_ID_1 = 0;
    private static final int NOTIFICATION_ID_2 = 1;
    private static final int NOTIFICATION_ID_3 = 2;
    private static final int NOTIFICATION_ID_4 = 3;
    private static final int NOTIFICATION_ID_5 = 4;
    private static final int NOTIFICATION_ID_6 = 5;
    private static final int NOTIFICATION_ID_7 = 6;
    private static final int NOTIFICATION_ID_8 = 7;

    private static int messageNum = 0;
    private Context context = this;
    private NotificationManager manager;
    private Bitmap icon;
    private static final int[] btns = new int[] { R.id.btn1, R.id.btn2,
                        R.id.btn3, R.id.btn4, R.id.btn5, R.id.btn6, R.id.btn7, R.id.btn8,
                        R.id.btn9 };

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

    private void init() {
        // 獲取通知服務
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 注冊監聽器
        for (int btn : btns) {
            findViewById(btn).setOnClickListener(this);
        }

        icon = BitmapFactory.decodeResource(getResources(),
                            R.drawable.ic_launcher);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn1:
            showNormal();
            break;
        case R.id.btn2:
            showBigView_Text();
            break;
        case R.id.btn3:
            showBigView_Pic();
            break;
        case R.id.btn4:
            showBigView_Inbox();
            break;
        case R.id.btn5:
            showCustomView();
            break;
        case R.id.btn6:
            backApp();
            break;
        case R.id.btn7:
            backScreen();
            break;
        case R.id.btn8:
            showProgressBar();
            break;
        case R.id.btn9:
            dismiss();
            break;
        default:
            Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
            break;
        }
    }

    private void dismiss() {
        manager.cancelAll();
    }

1. 普通通知

    private void showNormal() {

        Notification notification = new NotificationCompat.Builder(context)
                                .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                                .setTicker("showNormal").setContentInfo("contentInfo")
                                .setContentTitle("ContentTitle").setContentText("ContentText")
                                .setNumber(++messageNum)
                                .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                                .build();
        manager.notify(NOTIFICATION_ID_1, notification);
    }

2. 大文本樣式通知

private void showBigView_Text() {
    NotificationCompat.BigTextStyle textStyle = new BigTextStyle();
    textStyle
                .setBigContentTitle("BigContentTitle")
                .setSummaryText("SummaryText")
                .bigText(
                    "I am Big Texttttttttttttttttttttttttttttttttttttttttttt!!!!!!!!!!!!!!!!!!!......");
    Notification notification = new NotificationCompat.Builder(context)
                .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                .setTicker("showBigView_Text").setContentInfo("contentInfo")
                .setContentTitle("ContentTitle").setContentText("ContentText")
                .setStyle(textStyle)
                .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                .build();
        manager.notify(NOTIFICATION_ID_2, notification);
    }

3. 大圖樣式通知

private void showBigView_Pic() {
    NotificationCompat.BigPictureStyle pictureStyle = new BigPictureStyle();
    pictureStyle.setBigContentTitle("BigContentTitle")
                    .setSummaryText("SummaryText").bigPicture(icon);
    Notification notification = new NotificationCompat.Builder(context)
                .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                .setTicker("showBigView_Pic").setContentInfo("contentInfo")
                .setContentTitle("ContentTitle").setContentText("ContentText")
                .setStyle(pictureStyle)
                .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                .build();
        manager.notify(NOTIFICATION_ID_3, notification);
    }

4. 收件箱樣式通知

private void showBigView_Inbox() {
    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    inboxStyle.setBigContentTitle("BigContentTitle").setSummaryText(
                    "SummaryText");
    for (int i = 0; i < 5; i++)
            inboxStyle.addLine("news:" + i);
    Notification notification = new NotificationCompat.Builder(context)
                .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                .setTicker("showBigView_Inbox").setContentInfo("contentInfo")
                .setContentTitle("ContentTitle").setContentText("ContentText")
                .setStyle(inboxStyle)
                .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                .build();
        manager.notify(NOTIFICATION_ID_4, notification);
    }

5. 自定義通知

效果圖:

下麵對中間的播放按鈕做了一個簡單的點擊處理(點擊播放後請關閉下拉菜單,否則可能看不到 toast 提示):

private void showCustomView() {
        RemoteViews remoteViews = new RemoteViews(getPackageName(),
                            R.layout.custom_notification);
        Intent intent = new Intent(this, TestMusicControl.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                    intent, 0);
        remoteViews.setOnClickPendingIntent(R.id.paly_pause_music,
                    pendingIntent);
        NotificationCompat.Builder builder = new Builder(context);
        builder.setContent(remoteViews).setSmallIcon(R.drawable.music_icon)
                    .setLargeIcon(icon).setOngoing(true)
                    .setTicker("music is playing");
        manager.notify(NOTIFICATION_ID_8, builder.build());
    }

對應的佈局文件:

<?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="match_parent"
    android:gravity="center_vertical"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/songer_pic"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:src="@drawable/yan" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/last_music"
            android:layout_width="0dp"
            android:layout_height="48dp"
            android:layout_weight="1"
            android:src="@drawable/music_previous" />

        <ImageView
            android:id="@+id/paly_pause_music"
            android:layout_width="0dp"
            android:layout_height="48dp"
            android:layout_weight="1"
            android:src="@drawable/music_play" />

        <ImageView
            android:id="@+id/next_music"
            android:layout_width="0dp"
            android:layout_height="48dp"
            android:layout_weight="1"
            android:src="@drawable/music_next" />
    </LinearLayout>

</LinearLayout>

帶進度條的通知(常用於下載場景):

    private void showProgressBar() {

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(
                    context);
        builder.setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                    .setTicker("showProgressBar").setContentInfo("contentInfo")
                    .setOngoing(true).setContentTitle("ContentTitle")
                    .setContentText("ContentText");
        new Thread(new Runnable() {

            @Override
            public void run() {

                            int progress = 0;

                            for (progress = 0; progress < 100; progress += 5) {
                                //將setProgress的第三個參數設為true即可顯示為無明確進度的進度條樣式
                                builder.setProgress(100, progress, false);
                                manager.notify(NOTIFICATION_ID_7, builder.build());
                                try {
                                    // Sleep for 5 seconds
                                    Thread.sleep(2 * 1000);
                                } catch (InterruptedException e) {
                                    System.out.println("sleep failure");
                                }
                            }
                            builder.setContentTitle("Download complete")
                            .setProgress(0, 0, false).setOngoing(false);
                            manager.notify(NOTIFICATION_ID_7, builder.build());

            }
        }).start();
    }

點擊事件處理


一個常見需求是:新通知到達時,點擊它直接进入應用內的相應界面查看或處理;處理完按返回鍵回到應用主界面而不是桌面。典型場景就是收到短信,點擊進入閱讀頁,讀完按返回回到短信列表而非桌面。這需要區分兩種做法。

1. 返回應用主界面

    private void backApp() {

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack
        stackBuilder.addParentStack(OtherActivity.class);
        // Adds the Intent to the top of the stack
        Intent resultIntent = new Intent(this, OtherActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        // Gets a PendingIntent containing the entire back stack
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);

        Notification notification = new NotificationCompat.Builder(context)
                    .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                    .setTicker("backApp").setContentInfo("contentInfo")
                    .setContentTitle("ContentTitle").setContentText("ContentText")
                    .setContentIntent(resultPendingIntent).setAutoCancel(true)
                    .setDefaults(Notification.DEFAULT_ALL).build();
        manager.notify(NOTIFICATION_ID_5, notification);
        this.finish();
    }

同時需要在配置文件裡為用來展示詳情的 OtherActivity 聲明父子關係:

<activity
            android:name="com.example.notification.OtherActivity"
            android:label="@string/title_activity_other"
            android:parentActivityName=".MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
            </activity>

2. 點擊後直接返回桌面

另一些場景下,點擊通知會彈出一個獨立窗口用來展示完整消息,它與應用內其他 Activity 沒有關聯,按返回鍵應直接回到桌面。做法是用 setContentIntent,並在 Manifest 中對目標 Activity 做特殊配置:

private void backScreen() {
    Intent notifyIntent = new Intent(this, SpecialActivity.class);
    // Sets the Activity to start in a new, empty task
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    // Creates the PendingIntent
    PendingIntent notify_Intent = PendingIntent.getActivity(this, 0,
                    notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = new NotificationCompat.Builder(context)
                .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                .setTicker("backScreen").setContentInfo("contentInfo")
                .setContentTitle("ContentTitle").setContentText("ContentText")
                .setContentIntent(notify_Intent).setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL).build();
        manager.notify(NOTIFICATION_ID_6, notification);
        this.finish();
    }

配置文件:

<activity
            android:name="com.example.notification.SpecialActivity"
            android:excludeFromRecents="true"
            android:label="@string/title_activity_special"
            android:launchMode="singleTask"
            android:taskAffinity="" >

小結

通知體系看似簡單,細節卻不少:三個必填項、三種大布局樣式、自定義 RemoteViews、進度條動畫,以及最容易被忽略的返回棧行為。把 TaskStackBuilder 與 Activity 的 launchMode、taskAffinity 配置搭配好,才能給用戶一條順暢自然的返回路徑。

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