我正在使用这段代码,当应用程序位于前台时,它运行得很好。但应用程序期间发出的通知处于后台 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/