每天記錄學習的新知識 :通知(Notification)的使用方法

參考及轉載

轉載地址:Notification常見樣式總結
轉載:https://stackoverflow.com/questions/38016215/android-notificationmanagercompat-arenotificationsenabled-not-working/39486721
轉載:https://www.jianshu.com/p/92afa56aee05
轉載:Android開發——Notification通知的使用及NotificationCopat.Builder常用設置API

參考地址:Android Oreo 通知新特性,這坑老夫先踩了
參考地址:Android:檢查通知權限並跳轉到通知設置界面
參考地址:PendingIntent總結

基本用法

發送通知

    private void toNotification(Context context) {

        if (context == null) {
            LogUtils.w(TAG, "toNotification context = null");
            return;
        }

        //support應至少爲24,compileSdkVersion必須爲24
        NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
        boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled();

        if (areNotificationsEnabled) {

            LogUtils.i(TAG, "擁有通知的權限");

            Intent clickIntent = new Intent(); //點擊通知之後要發送的廣播
            int id = (int) (System.currentTimeMillis() / 1000);
            clickIntent.setAction(ACTION_NOTIFY_CLICKED_MESSAGE);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), id, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String channelId = "channelId" + System.currentTimeMillis();
                NotificationChannel channel = new NotificationChannel(channelId, context.getResources().getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
                manager.createNotificationChannel(channel);
                builder.setChannelId(channelId);
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                builder.setStyle(new NotificationCompat.BigTextStyle().bigText("不普通的內容," +
                        "不普通的內容,不普通的內容,不普通的內容,不普通的內容,"));
//                .setBigContentTitle("不普通的標題頭,不普通的標題頭不普通的標題頭不普通的標題頭不普通的標題頭")
            }

            builder
                    .setContentTitle("這個是個PT長度的TITLE")
//                    .setContentText("這個是個PT長度的CONTENT")
                    .setDefaults(NotificationCompat.FLAG_AUTO_CANCEL)
                    .setAutoCancel(true)
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setGroupSummary(false)// 強制設置不要摺疊
                    .setContentIntent(pendingIntent)
                    .setWhen(System.currentTimeMillis());
            manager.notify(1, builder.build());
        } else {
            LogUtils.w(TAG, "沒有通知的權限");
        }

    }

註冊和反註冊廣播

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notify);
        ButterKnife.bind(this);

        notificationReceiver = new NotificationReceiver();
        IntentFilter filter3 = new IntentFilter();
        filter3.addAction(ACTION_NOTIFY_CLICKED_MESSAGE);
        registerReceiver(notificationReceiver, filter3);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(notificationReceiver);
    }

自定義廣播接收器

    public class NotificationReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            LogUtils.i(TAG, "onReceive");
            if (intent != null && ACTION_NOTIFY_CLICKED_MESSAGE.equals(intent.getAction())) {
                LogUtils.i(TAG, "onReceive ACTION_NOTIFY_CLICKED_MESSAGE");

            }

        }


    }

效果圖

前兩個圖是vivo X20A上的效果圖,第三個效果是HUAWEI P30

技術點剖析

1 通知權限

        NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
        boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled();

轉載:https://stackoverflow.com/questions/38016215/android-notificationmanagercompat-arenotificationsenabled-not-working/39486721
需要判斷通知顯示的方法可用,需要:

android {    
    compileSdkVersion 24      
}    
dependencies {
     compile 'com.android.support:support-v4:24.0.0'
}

以上。

注意:areNotificationsEnabled 只對 API 19 及以上版本有效,低於API 19 會一直返回true

如果打開通知顯示,可以前往設置:

            LogUtils.w(TAG, "沒有通知的權限");

            Intent intent = new Intent();

            LogUtils.i(TAG, "通知權限未開啓,手機信息 ==" + "\n" +
                    "手機型號" + android.os.Build.MODEL + "\n" +
                    "SDK版本" + android.os.Build.VERSION.SDK + "\n" +
                    "系統版本" + android.os.Build.VERSION.RELEASE + "\n" +
                    "軟件包名" + getPackageName() + "\n"
            );

            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    LogUtils.i(TAG, "當前版本 API > 26");
                    intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
                    intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
                    intent.putExtra(Settings.EXTRA_CHANNEL_ID, getApplicationInfo().uid);
                } else {
                    LogUtils.i(TAG, "當前版本 API < 26");
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.putExtra("app_package", getPackageName());
                    intent.putExtra("app_uid", getApplicationInfo().uid);
                }
                startActivity(intent);
            } catch (Exception e) {
                LogUtils.w(TAG, "當前版本跳轉通知欄設置異常");
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            }

2 意圖(點擊事件)

2.1 調用

            Intent clickIntent = new Intent(); //點擊通知之後要發送的廣播
            int id = (int) (System.currentTimeMillis() / 1000);
            clickIntent.setAction(ACTION_NOTIFY_CLICKED_MESSAGE);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), id, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
.setContentIntent(pendingIntent)

2.2 獲取

PendingIntent的實例獲取一般有以下五種方法:

getActivity()
getActivities()
getBroadcast()
getService()
getForegroundService()

常用的有三種:

  1. getActivity
    從系統取得一個用於啓動一個Activity的PendingIntent對象

  2. getBroadcast
    從系統取得一個用於向BroadcastReceiver的Intent廣播的PendingIntent對象

  3. getService
    從系統取得一個用於啓動一個Service的PendingIntent對象

2.3 PendingIntent的參數

如上描述,PendingIntent 獲取的方式有多種。但是幾種獲取方式的參數都是互通的,都是 Context context, int requestCode, Intent intent, int flags.

如果想理解PendingIntent的參數含義,首先得了解一下什麼是相同的PendingIntent。

2.3.1 PendingIntent相同的標準

參考地址:PendingIntent總結

重點概念:

當PendingIntent中的Intent和requestCode都相同即說明這兩個是相同的PendingIntent
當Intent的componentName和intent-filter都相同即說明這兩個是相同的Intent

2.3.2 requestCode, 請求標識

所以,requestCode的作用:
在有兩個PendingIntent,並且兩個PendingIntent的intent相同的情況下,控制PendingIntent是否相同。

理解reqCode:

在這裏插入圖片描述

場景默認是 flag = FLAG_UPDATE_CURRENT,intent相同:

分析場景1:1579
此時,推送通知到通知欄,一切ok

分析場景2:1579 後 2579
通知欄收到1579後,未點擊;2579 通知到達通知欄。因爲都是潤滑油的變化,所以1579的點擊後的操作,要被2579覆蓋。requestCode 在這裏表示操作5。

分析場景3:1579後2579,再3679。
場景2中描述後,3679,因爲是汽油變化,所以不能刷新之前通知點擊後的操作,所以汽油的requestCode區別於潤滑油。6區別於5.

2.3.3 intent, 請求意圖

intent:調用意圖

component :

作用 :component用於明確指定需要啓動的目標組件

intent-filter:

作用:過濾Action、Category屬性

優點:解耦

2.3.3 flags 控制獲取 PendingIntent 的方式

  1. PendingIntent.FLAG_CANCEL_CURRENT
    如果當前已存在則取消當前的並返回一個新的 PendingIntent

  2. PendingIntent.FLAG_UPDATE_CURRENT
    如果已存在則更新之前的

  3. PendingIntent.FLAG_NO_CREATE
    如果已存在則返回當前存在的,否則返回 null

  4. PendingIntent.FLAG_ONE_SHOT
    表明這個 PendingIntent 只能用一次,觸發一次後自動 cancel

  5. PendingIntent.FLAG_IMMUTABLE
    表明這個PendingIntent 不可變

2.3.4 舉例理解 flags

2.3.4.1 FLAG_UPDATE_CURRENT

場景1:

requestCode 和 intent 相同,

clickIntent.putExtra(EXTRA_012, "content:" + EXTRA_012 +" "+ num);
manager.notify(num++, builder.build());

操作:

第一次通知發送後,不點擊;第二次通知發送後,分別點擊第一次和第二次。

結果:

第二次的通知中的extra值,會覆蓋第一次通知的extra的值。

場景2:

修改場景1中的代碼,修改requestCode可變:

和場景1相同的操作。

結果:

通知2,不會覆蓋掉通知1中,extra的value

結論:FLAG_UPDATE_CURRENT 在 PendingIntent 相同的條件下,會覆蓋Extra的value值

2.3.4.2 FLAG_CANCEL_CURRENT

場景3:

requestCode 和 intent 相同,

clickIntent.putExtra(EXTRA_012, "content:" + EXTRA_012 +" "+ num);
manager.notify(num++, builder.build());

操作:

第一次通知發送後,不點擊;第二次通知發送後,分別點擊第一次和第二次。

結果:

通知1,點擊後,有點擊回饋,通知欄會關閉,但是不會執行PendingIntent 動作;
通知2,點擊後會正常執行動作。

場景4:

修改requestCode爲可變。

此時PendingIntent 互不相同,不會產生影響,會都正常執行動作。

結論:FLAG_CANCEL_CURRENT在 PendingIntent 相同的條件下,點擊有回饋,但是會取消上個通知PendingIntent 執行

3 通知渠道(Notification Channels)

3.1 創建通知渠道

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "channelId" + System.currentTimeMillis();
            NotificationChannel channel =
             new NotificationChannel(channelId, context.getResources().getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
            manager.createNotificationChannel(channel);
            builder.setChannelId(channelId);
        }

轉載:https://www.jianshu.com/p/92afa56aee05

Android O 引入了 通知渠道(Notification Channels),以提供統一的系統來幫助用戶管理通知,如果是針對 android O 爲目標平臺時,必須實現一個或者多個通知渠道,以向用戶顯示通知。若並不以 Android O 爲目標平臺,當應用運行在 android O 設備上時,其行爲將與運行在 Android 7.0 上時相同。

作用:開發者可以爲需要發送的每個不同的通知類型創建一個通知渠道

所以,上面代碼會有問題,因爲channelId 每次都會隨機創建一個,導致應用每發送一次推送,即會創建一個渠道。

如圖 手機的通知管理中:

左圖中,通知類別會和發送通知的次數一樣多…
右圖是類別詳情,每種類別詳情都可以由用戶自由設置。

修改代碼:


    String channelId = "channelId1212" + "123456789";
    String channelId13 = "channelId1313" + "123456789";


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (requestCode == 1212) {
                NotificationChannel channel = new NotificationChannel(channelId, "普通推送", NotificationManager.IMPORTANCE_HIGH);
                manager.createNotificationChannel(channel);
                builder.setChannelId(channelId);
            } else if (requestCode == 1313) {
                NotificationChannel channel = new NotificationChannel(channelId13, "重要通道", NotificationManager.IMPORTANCE_HIGH);
                manager.createNotificationChannel(channel);
                builder.setChannelId(channelId13);
            }
        }

示例圖:

3.2 渠道詳細設置

參考地址:Android Oreo 通知新特性,這坑老夫先踩了

包含:
聲音

振動
在鎖屏上顯示
替換免打擾模式

        NotificationChannel channel = new NotificationChannel(channelId, "普通推送", NotificationManager.IMPORTANCE_HIGH);

        String description = "這是一個普通推送的渠道描述";
        channel.setDescription(description);

        // 設置通知出現時的閃燈(如果 android 設備支持的話)
        channel.enableLights(true);
        channel.setLightColor(Color.RED);

        // 設置通知出現時的震動(如果 android 設備支持的話)
        channel.enableVibration(true);
        channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

        // 覆蓋勿擾設置(無法更改)
        channel.setBypassDnd(true);

        // 屏幕鎖定時通知顯示方式(無法更改)
        /*
         *    @hide
         *@IntDef(prefix = {"VISIBILITY_"}, value = {
         *VISIBILITY_PUBLIC,
         *VISIBILITY_PRIVATE,
         *VISIBILITY_SECRET,
         *})
         */
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);

        //其中“lockscreenVisibility”和“setBypassDnd”是無法生效的,因爲從源碼中來看,只能被系統或排序服務(Android Notification Ranking Service)更改。

        manager.createNotificationChannel(channel);
        builder.setChannelId(channelId);

3.3 渠道推送權限(消息重要性)

Oreo不用Priority了,用importance,importance包含以下:

  • IMPORTANCE_NONE 關閉通知
  • IMPORTANCE_MIN 開啓通知,不會彈出,但沒有提示音,狀態欄中無顯示
  • IMPORTANCE_LOW 開啓通知,不會彈出,不發出提示音,狀態欄中顯示
  • IMPORTANCE_DEFAULT 開啓通知,不會彈出,發出提示音,狀態欄中顯示
  • IMPORTANCE_HIGH 開啓通知,會彈出,發出提示音,狀態欄中顯示
  • IMPORTANCE_MAX Unused,和IMPORTANCE_HIGH 類似

3.4 渠道組

修改上面代碼:

    // 通知渠道組的id.
    String groupId = "渠道組ID001";
    // 用戶可見的通知渠道組名稱.
    CharSequence groupName = "渠道組名字001";
        NotificationChannel channel = new NotificationChannel(channelId, "普通推送", NotificationManager.IMPORTANCE_HIGH);
        
        NotificationChannelGroup group = new NotificationChannelGroup(groupId, groupName);
        channel.setGroup(groupId);
        manager.createNotificationChannelGroup(group);
      
        manager.createNotificationChannel(channel);
        builder.setChannelId(channelId);

加入渠道組,是如下代碼:

        NotificationChannelGroup group = new NotificationChannelGroup(groupId, groupName);
        channel.setGroup(groupId);
        manager.createNotificationChannelGroup(group);

示意圖:

注意:上面示意圖是 vivo X20A 上的截圖;在HUAWEI P30上不能顯示出類別來,不知道怎麼搞

4 通知顯示效果

代碼轉載自:Notification常見樣式總結

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                builder.setStyle(new NotificationCompat.BigTextStyle().bigText("不普通的內容," +
                        "不普通的內容,不普通的內容,不普通的內容,不普通的內容,"));
//                .setBigContentTitle("不普通的標題頭,不普通的標題頭不普通的標題頭不普通的標題頭不普通的標題頭")
            }

4.1 文本

4.1.1 常規文本設置

Android 系統和機型影響比較大啊,在HUAWEI P30系統中,如下代碼和示意圖:

        //Ticker是狀態欄顯示的提示
        builder.setTicker("簡單Notification");
        //第一行內容  通常作爲通知欄標題
        builder.setContentTitle("標題");
        //第二行內容 通常是通知正文
        builder.setContentText("通知內容");
        //第三行內容 通常是內容摘要什麼的 在低版本機器上不一定顯示
        builder.setSubText("這裏顯示的是通知第三行內容!");
        //ContentInfo 在通知的右側 時間的下面 用來展示一些其他信息
        builder.setContentInfo("2");
        //number設計用來顯示同種通知的數量和ContentInfo的位置一樣,如果設置了ContentInfo則number會被隱藏
//                    builder.setNumber(2);
        //系統狀態欄顯示的小圖標
        builder.setSmallIcon(R.mipmap.ic_launcher);

效果圖:

這幾行,

builder.setTicker("簡單Notification");
builder.setContentInfo("2");

沒有效果。

4.1.2 長文本 BigTextStyle

在HUAWEI P30系統中,如下代碼和示意圖:

        builder.setContentTitle("BigTextStyle");
        builder.setContentText("BigTextStyle演示示例");
        builder.setSmallIcon(R.mipmap.ic_launcher);
        android.support.v4.app.NotificationCompat.BigTextStyle style = new android.support.v4.app.NotificationCompat.BigTextStyle();
        style.bigText("這裏是點擊通知後要顯示的正文,可以換行可以顯示很長很長很長很長很長很長很長很長很長很長很長很長很長很長很長很長很長很長");
        style.setBigContentTitle("點擊後的標題");
        //SummaryText沒什麼用 可以不設置
        style.setSummaryText("總結");
        builder.setStyle(style);                   

效果圖:

沒有效果的是:

        builder.setContentText("BigTextStyle演示示例");

4.1.3 分行顯示文本

        builder.setContentTitle("InboxStyle");
        builder.setContentText("InboxStyle演示示例");
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_a));
        android.support.v4.app.NotificationCompat.InboxStyle style = new android.support.v4.app.NotificationCompat.InboxStyle();
        style.setBigContentTitle("BigContentTitle")
                .addLine("第一行,第一行,第一行,第一行,第一行,第一行,第一行")
                .addLine("第二行")
                .addLine("第三行")
                .addLine("第四行")
                .addLine("第五行")
                .addLine("第6行")
                .setSummaryText("SummaryText");
        builder.setStyle(style);

效果:

這裏

builder.setContentText("InboxStyle演示示例");

就好用?

4.2 顯示圖片

效果:

顯示大圖:
就最大的那個圖。

builder.setStyle(new NotificationCompat.BigPictureStyle()
	.bigPicture(BitmapFactory.decodeResource(context.getResources(), R.drawable.navi_marker_current)));

顯示邊圖:
角標下面的圖標,不知道怎麼形容那個位置的圖片,隨便叫吧!

builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_a));

4.3 顯示進度條

        int progress = 43;
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_a));
        //禁止用戶點擊刪除按鈕刪除
        builder.setAutoCancel(false);
        //禁止滑動刪除
        builder.setOngoing(true);
        //取消右上角的時間顯示
        builder.setShowWhen(false);
        builder.setContentTitle("下載中..." + progress + "%");
        builder.setProgress(100, progress, false);
        builder.setContentIntent(pendingIntent);

需要注意:manager.notify(num++, builder.build()); 第一次參數代表通知欄ID,如果是進度條,需要在原ID上更新,而不是彈出新的通知,ID應該是定值。

4.4 橫幅通知

測試 HUAWEI P30,橫幅正常,同時通知欄內也會有這次通知。

        builder.setContentTitle("橫幅通知");
        builder.setContentText("請在設置通知管理中開啓消息橫幅提醒權限");
        builder.setDefaults(NotificationCompat.DEFAULT_ALL);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_a));
        //這句是重點
        builder.setFullScreenIntent(pendingIntent,false);
        builder.setAutoCancel(true);

效果:

橫幅不點擊或者划走(上劃取消),會一致存在。

如果點擊,橫幅和通知欄內的通知都會消失;如果划走,通知欄內的通知還會存在。

5 Notification 常用 API

5.1 NotificationCompat.Builder

NotificationCompat.Builder自動設置的默認值:

priority: PRIORITY_DEFAULT //通知的重要程度
when: System.currentTimeMillis() //時間
audio stream: STREAM_DEFAULT //音效 系統默認音效

5.1.1 點擊後消失

setAutoCancel(boolean autocancel)

5.1.2 設置自定義通知View

setContent(RemoteView view)

5.1.3 設置標題

setContentTitle(String string)

5.1.4 設置內容

setContentText(String string)

5.1.5 設置點擊內容後的跳轉(意圖)

setContentIntent(PendingIntent intent)

5.1.6 設置時間

setWhen(long when)

5.1.7 設置通知的重要程度(優先級)

Notification.PRIORITY_MAX 重要而緊急的通知,通知用戶這個事件是時間上緊迫的或者需要立即處理的。
Notification.PRIORITY_HIGH 高優先級用於重要的通信內容,例如短消息或者聊天,這些都是對用戶來說比較有興趣的
Notification.PRIORITY_DEFAULT 默認優先級用於沒有特殊優先級分類的通知
Notification.PRIORITY_LOW 低優先級可以通知用戶但又不是很緊急的事件。只顯示狀態欄圖標
Notification.PRIORITY_MIN 用於後臺消息 (例如天氣或者位置信息)。只有用戶下拉通知抽屜才能看到內容

setPriority(int pri)

5.1.8 設置樣式

setStyle(Style style)

5.1.9 設置鎖屏顯示

setVisibility(int visibility)

5.1.10 設置默認

Notification.DEFAULT_SOUND 添加默認聲音提醒
Notification.DEFAULT_VIBRATE 添加默認震動提醒
Notification.DEFAULT_LIGHTS 添加默認呼吸燈提醒
Notification.DEFAULT_ALL 同時添加以上三種默認提醒

setDefault(int defaults)

5.1.11 設置呼吸燈閃爍效果

setLight(int argb, int onMs, int offMs)

5.1.12 設置通知音效

setSound(Uri sound)

5.1.13 設置震動效果

setVibrate(long [] pattern)

5.1.14 設置通知類別

setCategory(String category)

5.1.15 設置通知欄顏色

setColor(int argb)

5.1.16 設置彈窗顯示(橫幅通知)

setFullScreenIntent(PendingIntent intent,boolean b)

5.1.17 設置小圖標

.setSmallIcon(R.mipmap.ic_launcher)

5.1.18 設置邊路圖標

.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))

5.1.19 強制設置不要摺疊

.setGroupSummary(false)

5.1.20 次要內容

.setSubText("這是通知的次要內容");

setContentInfo 在 api 24 被廢棄,不再顯示,用 setSubText 代替
setNumber 在 api 24 被廢棄,不再顯示

// 附加文本
builder.setContentInfo("INFO");
// 附加數字,等價於 setContentInfo, 爲了顯示效果用一個不同的字體尺寸顯示數字
builder.setNumber(123);

5.1.21 設置是否顯示時間

.setShowWhen(false);

5.1.22 進度條

.setProgress(max, progress, indeterminate);

5.1.23 狀態欄摘要

在 api 21 後不再顯示

.setTicker("this is ticker"); 

5.1.24 設置呼吸燈提醒只執行一次

.setOnlyAlertOnce(true);

5.1.25 取消通知事件

.setDeleteIntent(pi);

5.2 NotificationManager

5.2.1 獲取通知管理

NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

5.2.2 發送通知

如果已經發送過相同id的通知,新通知會替換掉原來的通知。

manager.notify(id, builder.build());

5.2.3 取消通知

manager.cancel (int id)

5.2.4 取消所有通知

manager.cancelAll ()

5.2.5 發送通知

manager.notify(String tag ,int id, Notification notification) 

5.2.6 取消通知

manager.cancel(String tag, int id)

5.2.7 設置渠道

manager.createNotificationChannel(channel);

5.2.7 設置渠道組

manager.createNotificationChannelGroup(new NotificationChannelGroup(groupId, groupName));

5.3 NotificationChannel

5.3.1 NotificationChannel

三個參數分別爲渠道ID,渠道名字,渠道重要度

  • IMPORTANCE_NONE 關閉通知
  • IMPORTANCE_MIN 開啓通知,不會彈出,但沒有提示音,狀態欄中無顯示
  • IMPORTANCE_LOW 開啓通知,不會彈出,不發出提示音,狀態欄中顯示
  • IMPORTANCE_DEFAULT 開啓通知,不會彈出,發出提示音,狀態欄中顯示
  • IMPORTANCE_HIGH 開啓通知,會彈出,發出提示音,狀態欄中顯示
NotificationChannel(String id,CharSequence name, int importance)

5.3.2 綁定渠道組

channel.setGroup("測試組ID");

5.3.3 設置描述

channel.setDescription(description);

5.3.4 設置通知出現時的閃燈(如果 android 設備支持的話)

 channel.enableLights(true);

5.3.5 設置閃燈顏色

channel.setLightColor(Color.RED);

5.3.6 設置通知出現時的震動(如果 android 設備支持的話)

 channel.enableVibration(true);

5.3.7 震動頻率

 channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

5.3.8 覆蓋勿擾設置(無法更改)

channel.setBypassDnd(true);

5.3.8 屏幕鎖定時通知顯示方式(無法更改)

VISIBILITY_PUBLIC,
VISIBILITY_PRIVATE,
VISIBILITY_SECRET,

channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章