描述:使用Notifaction时,使用到PendingIntent中使用intent传值的问题,接收Activity接收时获取到的内容为null。
解决:
flags有四个取值:
int FLAG_CANCEL_CURRENT:如果该PendingIntent已经存在,则在生成新的之前取消当前的。
int FLAG_NO_CREATE:如果该PendingIntent不存在,直接返回null而不是创建一个PendingIntent。
int FLAG_ONE_SHOT:该PendingIntent只能用一次,在send()方法执行后,自动取消。
int FLAG_UPDATE_CURRENT:如果该PendingIntent已经存在,则用新传入的Intent更新当前的数据。
我们需要把最后一个参数改为PendingIntent.FLAG_UPDATE_CURRENT,这样在启动的Activity里就可以用接收Intent传送数据
的方法正常接收。
发送方code:
Intent intent = new Intent(context, XXActivity.class);intent.putExtra("recFile", recName);PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);Notification.Builder builder = new Notification.Builder(context);builder.setTicker("新的通知");builder.setSmallIcon(R.drawable.ic_launcher);builder.setContentTitle("收到新的通知");builder.setContentText("您有一条新的通知");builder.setContentIntent(pendingIntent);Notification notification = builder.build();notification.flags = Notification.FLAG_AUTO_CANCEL;manager.notify(NOTIFACTION_FLAG_CODE, notification);
接收方code:
String recFileName = getIntent().getStringExtra("recFile");if (recFileName != null) {//处理逻辑...}
