我有一个应用程序,它显示从后端生成的通知,每个通知都包含不同的数据,并且在单击时应在通知页面上显示适当的内容。
例如:假设我收到3条通知,其中一个具有ID为1的红色数据,然后我得到另一个ID为2的BLUE,另一个具有ID 3的数据GREEN,所以每当我单击任何通知时,都说RED,BLUE或绿色,它将始终打开红色的通知页面
@Override
public void onReceive(Context context, Bundle bundle) {
ctx = context;
model = new Model();
String subtitle = bundle.getString("subtitle");
String title = bundle.getString("title");
String body = bundle.getString("body");
String eventJsonString = bundle.getString("extraData");
JSONObject extraObj = null;
try {
extraObj = new JSONObject(eventJsonString);
} catch (JSONException e) {
e.printStackTrace();
}
String Id = null;
try {
deviceId = extraObj.getString("Id");
} catch (JSONException e) {
e.printStackTrace();
}
if( Id == null){
Log.d("Notification","ready notification "+bundle.get("Id"));
Intent result = new Intent();
result.setAction(ServiceConstants.NOTIFICATION_RECEIVED);
LocalBroadcastManager.getInstance(context).sendBroadcast(result);
}
else{
isNotification = true;
try {
model.setId(Integer.parseInt(extraObj.getString("Id")));
} catch (Exception e) {
e.printStackTrace();
}
//Type is not available with notification bundle
try {
model.setType(extraObj.getString("Type"));
} catch (Exception e) {
e.printStackTrace();
model.setType("NA");
}
}
sendNotification(title, subtitle, body, context);
}
private void sendNotification(String title, String subtitle, String body, Context context) {
Intent intent = null;
if(isNotification){
intent = new Intent(ctx, NotificationActivity.class);
intent.putExtra("model", model);
}
else{
intent = new Intent(ctx, MyActivity.class);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mNotificationManager = (NotificationManager)
ctx.getSystemService(NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
String id = "com.honeywell.fire.crs";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(id, title, NotificationManager.IMPORTANCE_DEFAULT);
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setLightColor(Color.GREEN);
mNotificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.launcher_icon)
.setContentTitle(title)
.setChannelId(id)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(subtitle +"\n" + body))
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentText(body);
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
int random = (int) (Math.random() * 50 + 1);
mNotificationManager.notify(random, mBuilder.build());
}
在此处传递唯一ID