1. 程式人生 > 實用技巧 >Android通知

Android通知

Andorid通知

需要使用 NotificationCompat.Builder 物件設定通知內容和渠道。

  • 小圖示,通過 setSmallIcon() 設定。這是所必需的唯一使用者可見內容。
  • 標題,通過 setContentTitle() 設定。
  • 正文文字,通過 setContentText() 設定。
  • 通知優先順序,通過 setPriority() 設定。優先順序確定通知在 Android 7.1 和更低版本上的干擾程度。(對於 Android 8.0 和更高版本,必須設定渠道重要性,如下一節中所示。)
    請注意,NotificationCompat.Builder 建構函式要求您提供渠道 ID。這是相容 Android 8.0(API 級別 26)及更高版本所必需的,但會被較舊版本忽略。

相應通知的Activity一般有兩種

  • 專用於響應通知的 Activity。使用者在正常使用應用時不會無緣無故想導航到這個 Activity,因此該 Activity 會啟動一個新任務,而不是新增到應用的現有任務和返回堆疊。
  • 應用的常規應用流程中存在的 Activity。在這種情況下,啟動 Activity 時應建立返回堆疊,以便保留使用者對返回和向上按鈕的預期。
    以下示例顯示瞭如何建立包含下列內容的通知:
  public void createAndUseNotification(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        /* intent 中可以存放一些引數  使得使用者從通知進入activity的時候 可以進行一些 初始化 */
        intent.putExtra("channel", "notification");
        TaskStackBuilder builder1 = TaskStackBuilder.create(context);
        builder1.addNextIntent(intent);
        PendingIntent pendingIntent = builder1.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);
        builder.setSmallIcon(R.drawable.ic_launcher_background)      //  通知的小圖示 必填
                .setContentText("親,到了填寫消費金額的時間了")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)    //通知的優先順序
                .addAction(R.drawable.ic_launcher_background,"確定",pendingIntent)// 設定按鈕   最多有三個按鈕 
                .addAction(R.drawable.ic_launcher_background,"取消",pendingIntent)//設定按鈕
                .setContentIntent(pendingIntent)                     //設定點按操作,pendingIntent為點選後開啟Activity操作
                .setAutoCancel(true);                                //點選後自動消失
        Notification notification = builder.build();
        NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
        /*
            notify用於顯示通知 第一個引數 id  更新或者移除通知 要用到它
            managerCompat.cancel(int  id)移除通知
            managerCompat.notify(id,notification)可以用來移除通知,也可以用來過更新通知,只需傳入相同的id,便會進行替換。
        
        */
        managerCompat.notify(1, notification);
      
    }

從 Android 8.1(API 級別 27)開始,應用每秒最多隻能發出一次通知提示音。如果應用在一秒內發出了多條通知,這些通知都會按預期顯示,但是每秒中只有第一條通知發出提示音。

建立渠道並設定重要性

必須先通過向 createNotificationChannel() 傳遞 NotificationChannel 的例項在系統中註冊應用的通知渠道,然後才能在 Android 8.0 及更高版本上提供通知。由於您必須先建立通知渠道,然後才能在 Android 8.0 及更高版本上釋出任何通知,因此應在應用啟動時立即執行這段程式碼。反覆呼叫這段程式碼是安全的,因為建立現有通知渠道不會執行任何操作。請注意,NotificationChannel 建構函式需要一個 importance,它會使用 NotificationManager 類中的一個常量。此引數確定出現任何屬於此渠道的通知時如何打斷使用者,但您還必須使用 setPriority() 設定優先順序,才能支援 Android 7.1 和更低版本。

建立渠道示例

 public void createNotificationChannel(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "channel_name";
            String description = "channel_description";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

新增操作按鈕

一個通知最多可以提供三個操作按鈕,讓使用者能夠快速響應,例如暫停提醒,甚至回覆簡訊。但這些操作按鈕不應該重複使用者在點按通知時執行的操作。
如需新增操作按鈕,請呼叫NotificationCompat.Builder的 addAction()方法。這就像在設定通知的預設點按操作,不同的是不會啟動 Activity,而是可以完成各種其他任務,例如啟動在後臺執行作業的 BroadcastReceiver,這樣該操作就不會干擾已經開啟的應用。
在 Android 10(API 級別 29)和更高版本中,如果應用不提供自己的通知操作按鈕,則平臺會自動生成通知操作按鈕。如果您不希望應用通知顯示任何建議的回覆或操作,可以使用 setAllowGeneratedReplies() 和 setAllowSystemGeneratedContextualActions() 選擇停用系統生成的回覆和操作。

直接添加回復操作

  • 建立一個可新增到通知操作的 RemoteInput.Builder 例項。此類的建構函式接受系統用作文字輸入鍵的字串。之後,手持式裝置應用使用該鍵檢索輸入的文字。
  • 為回覆操作建立 PendingIntent。
  • 使用 addRemoteInput() 將 RemoteInput 物件附加到操作上
  • 對通知應用操作併發出通知。

請呼叫 RemoteInput.getResultsFromIntent() 並傳入 BroadcastReceiver 收到的 Intent:
處理完文字後,必須使用相同的 ID 和標記(如果使用)呼叫 NotificationManagerCompat.notify() 來更新通知。若要隱藏直接回復介面並向用戶確認他們的回覆已收到並得到正確處理,則必須完成該操作。
在處理這個新通知時,請使用傳遞給接收者的 onReceive() 方法的上下文。
您還應通過呼叫 setRemoteInputHistory() 將回復附加到通知底部。但如果要構建即時通訊應用,應建立訊息式通知,並在會話中附加新訊息。

        RemoteInput.Builder remoteInputBuilder = new RemoteInput.Builder("res");
        RemoteInput build = remoteInputBuilder.build();
        Intent intent1 = new Intent();
        intent1.setAction("aa");
        PendingIntent broadcast = PendingIntent.getBroadcast(this, 11, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action reply = new NotificationCompat.Action.Builder(R.drawable.ic_launcher_foreground, "回覆", broadcast).addRemoteInput(build).build();


    public  class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle resultsFromIntent = RemoteInput.getResultsFromIntent(intent);
            if (resultsFromIntent != null) {
                Log.d(TAG, "onReceive: " + resultsFromIntent.getString("res"));
                Notification notificationCompat = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setContentText("回覆成功")
                        .setAutoCancel(true)
                        .build();
                notificationManager.notify(1,notificationCompat);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                notificationManager.cancel(1);
            }
        }
    }