簡體   English   中英

如何在手機鎖定時顯示彈出通知?

[英]How to show a pop-up notification when the phone is locked?

我想在鎖定屏幕上將此通知顯示為彈出窗口或警報對話框。

public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    String title = remoteMessage.getNotification().getTitle();
    String body = remoteMessage.getNotification().getBody();

    Map<String, String> extraData = remoteMessage.getData();

    String brandID = extraData.get("brandID");
    String category = extraData.get("category");

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "TAC")
            .setContentText(body)
            .setContentTitle(title)
            .setSound(defaultSoundUri)
            .setDefaults(Notification.DEFAULT_ALL) // must requires VIBRATE permission
            .setPriority(NotificationCompat.PRIORITY_HIGH) //must give priority to High, Max which will considered as heads-up notification
            .setDefaults(Notification.DEFAULT_ALL)
            .setSmallIcon(R.drawable.ic_launcher_background);

    Intent intent;
    if(category.equals("shoes")){
        intent = new Intent(this, ReceiveNotification.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    }
    else {
        intent = new Intent(this, ReceiveNotification.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    intent.putExtra("brandID", brandID);
    intent.putExtra("category", category);

    PendingIntent pendingIntent
            = PendingIntent.getActivity(this, 10, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationChannel notificationChannel = new NotificationChannel("TAC", "demo", NotificationManager.IMPORTANCE_HIGH);
        manager.createNotificationChannel(notificationChannel);
    }
    int id = (int) System.currentTimeMillis();
    manager.notify(id, builder.build());

}

要從鎖定屏幕控制通知中可見的詳細程度,請調用setVisibility()並指定以下值之一:

  • VISIBILITY_PUBLIC顯示通知的完整內容。
  • VISIBILITY_SECRET不會在鎖定屏幕上顯示此通知的任何部分。
  • VISIBILITY_PRIVATE顯示基本信息,例如通知的圖標和內容標題,但隱藏通知的全部內容。

設置VISIBILITY_PRIVATE ,您還可以提供隱藏某些詳細信息的通知內容的替代版本。 例如,短信應用可能會顯示一條通知,顯示您有 3 條新短信,但隱藏了消息內容和發件人。 要提供此替代通知,首先像往常一樣使用 NotificationCompat.Builder 創建替代通知。 然后使用setPublicVersion()將替代通知附加到普通通知。

但是,用戶始終可以最終控制他們的通知是否在鎖定屏幕上可見,甚至可以根據您應用的通知渠道進行控制。

有關更多詳細信息, 請單擊此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM