android - PendingIntent传递数据
阿神
阿神 2017-04-17 13:10:05
[Android讨论组]

1.使用intent传递数据的话,在Activity1中使用startActivity(intent)来启动活动,然后在Activity2中使用getIntent()来获取传递过来的Intent,但是如果Activity1使用的是PendingIntent来传递数据的话,在Activity2中如何获取Intent?

2.如果需要让Activity2返回数据给Activity1,则在Activity1中使用startActivityForResult方法,并实现onActivityResult方法,但是如果使用的是PendingIntent来传递数据的话该怎么办,该怎么返回数据给Activity1?

阿神
阿神

闭关修行中......

全部回复(3)
巴扎黑

问题1分析:两种方式以同样的方法获取extra数据

PendingIntent.getActivity()打包了一个Context.startActivity()方法的调用,该方法告诉操作系统『我需要启动一个Activity』,随后调用PendingIntent.send()方法时,操作系统会按照我们的要求发送原来封装的intent。
所以下面的代码都可以启动目标Activity:

Intent intent = new Intent(context, class);
intent.putExtra(key, value);
// 可以这样启动:
PendingIntent.getActivity(context, 0, intent, 0).send();
// 也可以这样启动:
startActivity(intent);

所以目标Activity都以同样的方式获取extra数据:getIntent().getExtras().getInt(key);

但是使用PendingIntent需要特别注意:

  1. 获取的extra数据很可能是旧的
    考虑这样一种使用情景:列表-详情界面,点击某个条目跳到详情界面。先点击了item 1 跳到对应的详情界面;然后点击item 2,这时仍然跳到1对应的界面。
    原因是PendingIntent中的intent的extra的数据未被更新。
    API这样描述PendingIntent.getActivity()的返回值,返回已存在的,或者匹配新参数的,『Returns an existing or new PendingIntent matching the given parameters.』
    那么怎样才能匹配新参数呢?把第4个参数从0改成PendingIntent.FLAG_UPDATE_CURRENT.

  2. 为了安全因素,最好只发送显示的intent
    API这样说:『For security reasons, the android.content.Intent you supply here should almost always be an explicit intent...』
    具体原因不清楚,但按照API讲的去做总归是没错的。

android.app.PendingIntent源码链接

问题2分析:两种方式以同样的方法返回result

对于显示Intent:setResult(resultCode, intent);
我仅对隐式的Intent做了测试:启动联系人列表,选择一个联系人后返回,可以获取联系人的信息:

Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
// 这样可以,第2个参数是requestCode
startActivityForResult(i, REQUEST_CONTACT);
// 这样也可以,第2个参数同样是requestCode,但奇怪的是联系人列表弹出来两次:
PendingIntent.getActivity(getActivity(), REQUEST_CONTACT, i, PendingIntent.FLAG_UPDATE_CURRENT).send();

然后在void onActivityResult(int requestCode, int resultCode, Intent data)中根据resultCode做相应的处理。

总结:还是让PendingIntent做它“字面上”该做的事情为好,比如通过AlarmManager定时做的任务,通过NotificationManager发送消息到通知栏,一种pending状态。让startActivity启动应用内的Activity,启动其它应用:读取联系人、调用摄像头、发送社交圈,等等,需要立刻响应的任务。

大家讲道理

PendingIntent一般是用来给Notification这种组件用的吧?
我想详细了解下您的应用场景。
因为一般activity是不会直接使用到PendingIntent的。
我希望能得到更多的信息来帮您解决问题,谢谢。

高洛峰

android 有个message bus第三方的lib,推荐你使用,可以直接activity之间互传数据

http://square.github.io/otto/
https://github.com/greenrobot/EventBus
等等

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号