首页 > 技术文章 > PendingIntent传值接收时为null

yuzhongzheng 2016-04-20 14:32 原文

时间:2016-4-20 11:01:20

描述:使用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:
    
  1. Intent intent = new Intent(context, XXActivity.class);
  2. intent.putExtra("recFile", recName);
  3. PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
  4. NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  5. Notification.Builder builder = new Notification.Builder(context);
  6. builder.setTicker("新的通知");
  7. builder.setSmallIcon(R.drawable.ic_launcher);
  8. builder.setContentTitle("收到新的通知");
  9. builder.setContentText("您有一条新的通知");
  10. builder.setContentIntent(pendingIntent);
  11. Notification notification = builder.build();
  12. notification.flags = Notification.FLAG_AUTO_CANCEL;
  13. manager.notify(NOTIFACTION_FLAG_CODE, notification);

接收方code:
    
  1. String recFileName = getIntent().getStringExtra("recFile");
  2. if (recFileName != null) {
  3. //处理逻辑...
  4. }



来自为知笔记(Wiz)


推荐阅读