我有一个在多种模式下使用的 Activity ,所以我必须这样做:
Intent i = new Intent(MainListActivity.this,MainActivity.class);
extras.putInt("id", c.getId());
extras.putInt("mode", AREA_MODE);
i.putExtra("extras", extras);
startActivity(i);
在 onCreate
中:
Intent i = this.getIntent();
extras = i.getBundleExtra("extras");
if(extras!=null){
id = extras.getInt("id", -1);
mode = extras.getInt("mode", COUNTRY_MODE);
}
但是 intent extras 总是空的。我错过了什么吗?有什么办法吗?
编辑:出于某种原因,getIntent()
方法返回之前的 Intent
,在我的例子中没有额外的(主要 Intent )。我想找出原因。
最佳答案
啊哈!我刚刚调试了这个问题。结果是由于一个微妙的细节documented in PendingIntent .
- PendingIntent 是对系统维护 token 的引用。因此,即使发送进程重新启动,重建类似的 Intent 也会检索到原始的 PendingIntent。然后发送方可以取消或更改它。
- 相似的 Intent == 相同的操作、操作、数据、类别、组件和标志。额外的不算!
- 仅在 Extras 方面不同的 Intent 都会检索相同的 token 。
A common mistake people make is to create multiple PendingIntent objects with Intents that only vary in their "extra" contents, expecting to get a different PendingIntent each time. This does not happen.
修复 1:制作一个不同 PendingIntent。它必须具有不同的操作、操作、数据、类别、组件或标志——或请求代码整数。
修复 2:使用 FLAG_CANCEL_CURRENT
或 FLAG_UPDATE_CURRENT
取消或修改任何现有的 PendingIntent。
这两个修复产生的结果略有不同。无论哪种方式,您的新 Extras 都应该通过。
关于android - 无法检索 Intent 的额外内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4898271/