1. 程式人生 > >Android開發中Notification通知欄的基本用法(總結)

Android開發中Notification通知欄的基本用法(總結)

1、Notification的基本使用流程

狀態通知欄主要涉及到2個類:Notification 和NotificationManager

Notification:通知資訊類,它裡面對應了通知欄的各個屬性

NotificationManager:是狀態列通知的管理類,負責發通知、清除通知等操作。

使用的基本流程:

  • Step1. 獲得NotificationManager物件:NotificationManager mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  • Step 2. 建立一個通知欄的Builder構造類:Notification.Builder mBuilder = new Notification.Builder(this);
  • Step 3. 對Builder進行相關的設定,比如標題,內容,圖示,動作等!
  • Step 4.呼叫Builder的build()方法為notification賦值
  • Step 5.呼叫NotificationManager的notify()方法傳送通知!
  • PS:另外我們還可以呼叫NotificationManager的cancel()方法取消通知

2、設定相關的一些方法:

Notification.Builder mBuilder = new Notification.Builder(this);

後再呼叫下述的相關的方法進行設定:常用的方法如下:

  • setContentTitle(CharSequence):設定標題
  • setContentText(CharSequence):設定內容
  • setSubText(CharSequence):設定內容下面一小行的文字
  • setTicker(CharSequence):設定收到通知時在頂部顯示的文字資訊
  • setWhen(long):設定通知時間,一般設定的是收到通知時的System.currentTimeMillis()
  • setSmallIcon(int):設定右下角的小圖示,在接收到通知的時候頂部也會顯示這個小圖示
  • setLargeIcon(Bitmap):設定左邊的大圖示
  • setAutoCancel(boolean):使用者點選Notification點選面板後是否讓通知取消(預設不取消)
  • setDefaults(int):向通知新增聲音、閃燈和振動效果的最簡單、使用預設(defaults)屬性,可以組合多個屬性,
    Notification.DEFAULT_VIBRATE(新增預設震動提醒);
    Notification.DEFAULT_SOUND(新增預設聲音提醒);
    Notification.DEFAULT_LIGHTS(新增預設三色燈提醒)
    Notification.DEFAULT_ALL(新增預設以上3種全部提醒)
  • setVibrate(long[]):設定振動方式,比如:
    setVibrate(new long[] {0,300,500,700});延遲0ms,然後振動300ms,在延遲500ms,接著再振動700ms,關於Vibrate用法後面會講解!
  • setLights(int argb, int onMs, int offMs):設定三色燈,引數依次是:燈光顏色,亮持續時間,暗的時間,不是所有顏色都可以,這跟裝置有關,有些手機還不帶三色燈;另外,還需要為Notification設定flags為Notification.FLAG_SHOW_LIGHTS才支援三色燈提醒!
  • setSound(Uri):設定接收到通知時的鈴聲,可以用系統的,也可以自己設定,例子如下:
    .setDefaults(Notification.DEFAULT_SOUND) //獲取預設鈴聲
    .setSound(Uri.parse("file:///sdcard/xx/xx.mp3")) //獲取自定義鈴聲
    .setSound(Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "5"))//獲取Android多媒體庫內的鈴聲

  • setOngoing(boolean):設定為ture,表示它為一個正在進行的通知。他們通常是用來表示一個後臺任務,使用者積極參與(如播放音樂)或以某種方式正在等待,因此佔用裝置(如一個檔案下載,同步操作,主動網路連線)

  • setProgress(int,int,boolean):設定帶進度條的通知引數依次為:進度條最大數值,當前進度,進度是否不確定如果為確定的進度條:呼叫setProgress(max, progress, false)來設定通知,在更新進度的時候在此發起通知更新progress,並且在下載完成後要移除進度條,通過呼叫setProgress(0, 0, false)既可。如果為不確定(持續活動)的進度條,這是在處理進度無法準確獲知時顯示活動正在持續,所以呼叫setProgress(0, 0, true),操作結束時,呼叫setProgress(0, 0, false)並更新通知以移除指示條
  • setContentIntent(PendingIntent):PendingIntent和Intent略有不同,它可以設定執行次數,主要用於遠端服務通訊、鬧鈴、通知、啟動器、簡訊中,在一般情況下用的比較少。比如這裡通過Pending啟動Activity:getActivity(Context, int, Intent, int),當然還可以啟動Service或者BroadcastPendingIntent的位識別符號(第四個引數):
    FLAG_ONE_SHOT 表示返回的PendingIntent僅能執行一次,執行完後自動取消
    FLAG_NO_CREATE 表示如果描述的PendingIntent不存在,並不建立相應的PendingIntent,而是返回NULL
    FLAG_CANCEL_CURRENT 表示相應的PendingIntent已經存在,則取消前者,然後建立新的PendingIntent,這個有利於資料保持為最新的,可以用於即時通訊的通訊場景
    FLAG_UPDATE_CURRENT 表示更新的PendingIntent
    使用示例:

    //點選後跳轉ActivityIntent intent =newIntent(context,XXX.class);PendingIntent pendingIntent =PendingIntent.getActivity(context,0, intent,0);  
    mBuilder.setContentIntent(pendingIntent)
  • setPriority(int):設定優先順序:

    優先順序使用者
    MAX重要而緊急的通知,通知使用者這個事件是時間上緊迫的或者需要立即處理的。
    HIGH高優先順序用於重要的通訊內容,例如短訊息或者聊天,這些都是對使用者來說比較有興趣的。
    DEFAULT預設優先順序用於沒有特殊優先順序分類的通知。
    LOW低優先順序可以通知使用者但又不是很緊急的事件。
    MIN用於後臺訊息 (例如天氣或者位置資訊)。最低優先順序通知將只在狀態列顯示圖示,只有使用者下拉通知抽屜才能看到內容。
    對應屬性:Notification.PRIORITY_HIGH...

例項效果圖如下:

MainActivity.java的程式碼如下:

package com.deepreality.notificationdemo;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Context mContext;
    private NotificationManager mNManager;
    private Notification notify1;
    Bitmap LargeBitmap = null;
    private static final int NOTIFYID_1 = 1;

    private Button btnNotificationShow, btnNotificationClose;

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

        componentInit();
        componentAddOnClickListener();

        mContext = MainActivity.this;
        //獲得通知訊息管理類物件
        mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //獲取大圖示
        LargeBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.iv_lol_icon1);
    }

    public void componentInit() {
        btnNotificationShow = findViewById(R.id.main_btnNotificationShow);
        btnNotificationClose = findViewById(R.id.main_btnNotificationClose);
    }

    public void componentAddOnClickListener() {
        btnNotificationShow.setOnClickListener(this);
        btnNotificationClose.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_btnNotificationShow:{
                //定義一個PendingIntent點選Notification後啟動一個Activity
                Intent intent = new Intent(MainActivity.this,NotificationActivity.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);

                //設定圖片,通知標題,傳送時間,提示方式等屬性
                Notification.Builder builder = new Notification.Builder(mContext);
                builder.setContentTitle("北極熊也有微笑")  //標題
                        .setContentText("北極熊是本人認為最棒的動物,沒有之一")   //內容
                        .setSubText("--北極熊很Happy~")     //內容下面的一小段文字
                        .setTicker("收到北極熊也有微笑發來的的訊息~")      //收到資訊後狀態列顯示的文字資訊
                        .setWhen(System.currentTimeMillis())    //系統顯示時間
                        .setSmallIcon(R.mipmap.ic_launcher)     //收到資訊後狀態列顯示的小圖示
                        .setLargeIcon(LargeBitmap)      //大圖示
                        .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //設定預設的三色燈與振動器
                        .setDefaults(Notification.DEFAULT_SOUND)    //設定系統的提示音
                        .setAutoCancel(true);       //設定點選後取消Notification
                builder.setContentIntent(pendingIntent);    //繫結PendingIntent物件

                notify1 = builder.build();
                mNManager.notify(NOTIFYID_1, notify1);
                break;
            }
            case R.id.main_btnNotificationClose:{
                //除了可以根據ID來取消Notification外,還可以呼叫cancelAll();關閉該應用產生的所有通知
                mNManager.cancel(NOTIFYID_1);//取消Notification
                //mNManager.cancelAll();//關閉該應用產生的所有通知
                break;
            }
            default:break;
        }

    }
}
備註:其中相關的Activity以及圖片等其他檔案,自行處理。