应用程序期间的 Android 通知处于后台, Intent 数据为空

标签 android notifications

我正在使用这段代码,当应用程序位于前台时,它运行得很好。但应用程序期间发出的通知处于后台 Intent 没有任何数据。

 Intent intent = new Intent(this, SplashActivity.class);

    intent.putExtra(Constant.device_id,deviceId);
    intent.putExtra(Constant.isFromPush,true);
    intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    String channelId = getString(R.string.default_notification_channel_id);
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(title_)
                    .setContentText(message)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId,
                getString(R.string.app_name),
                NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    notificationManager.notify(new Random().nextInt( 2000 ) /* ID of notification */, notificationBuilder.build());

最佳答案

要在应用程序处于后台时处理 Intent 数据,您需要做一些额外的事情。 您的响应中应该有“数据”键才能使其处于 Activity 状态。就像,

{
"notification": {
    "key_1": "value_1",
    "key_2": "value_2"
 },
"data": {
    "key_1": "value_1",
    "key_2": "value_2"
 },

}

并且您需要获取启动 Activity 的 onCreate 方法中的值。 启动 Activity 是哪个<intent-filter>包含

 <category android:name="android.intent.category.LAUNCHER" />

接收数据,

Bundle bundle = getIntent().getExtras();
if (bundle != null) {
   //bundle contains all info of "data" field of the notification
}

In background, app receives notification payload in the notification tray, and only handle data payload when the user taps on the notification

关于应用程序期间的 Android 通知处于后台, Intent 数据为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54997485/

相关文章:

android - 服务停止时如何隐藏状态栏上的gps图标?

iphone - 如何使用推送通知

ios - 如果用户不打开应用程序而忽略了太多通知,iOS 是否会停止发送静默推送通知?

android - SERVICE_VERSION_UPDATE_REQUIRED 和 Google play 服务在 android 中集成 Google Plus 时已过时

android - 按下 .addAction() 时 BroadcastReceiver 未收到

jquery - 重定向后在目标页面上显示通知

python - 多个 WindowsBaloonTip/TrayTip 通知?

android - 如何让用户取消 Android 中的进度通知?

android - 如何缩短 Android 开发时间

java - 我无法从 AsyncTask 获得结果?