正确的代码如下所示:
PendingIntent contentIntent = PendingIntent.getActivity(TestAty.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
MyCode
之前的错误代码如下所示:
PendingIntent contentIntent = PendingIntent.getActivity(TestAty.this, 0, intent, 0);
MyCode
最后一位是flag,一定要设置一下,否则不能成功传递Extras。
下面是flag的文档描述:
public static final int FLAG_CANCEL_CURRENT
Since: API Level 1
Flag for use with getActivity(Context, int, Intent, int)
, getBroadcast(Context, int, Intent, int)
, and getService(Context, int, Intent, int)
: if the described PendingIntent already exists, the current one is canceled before generating a new one. You can use this to retrieve a new PendingIntent when you are only changing the extra data in the Intent; by canceling the previous pending intent, this ensures that only entities given the new data will be able to launch it. If this assurance is not an issue, consider FLAG_UPDATE_CURRENT
.
Constant Value: 268435456 (0x10000000)
public static final int FLAG_NO_CREATE
Since: API Level 1
Flag for use with getActivity(Context, int, Intent, int)
, getBroadcast(Context, int, Intent, int)
, and getService(Context, int, Intent, int)
: if the described PendingIntent does not already exist, then simply return null instead of creating it.
Constant Value: 536870912 (0x20000000)
public static final int FLAG_ONE_SHOT
Since: API Level 1
Flag for use with getActivity(Context, int, Intent, int)
, getBroadcast(Context, int, Intent, int)
, and getService(Context, int, Intent, int)
: this PendingIntent can only be used once. If set, after send()
is called on it, it will be automatically canceled for you and any future attempt to send through it will fail.
Constant Value: 1073741824 (0x40000000)
public static final int FLAG_UPDATE_CURRENT
Since: API Level 3
Flag for use with getActivity(Context, int, Intent, int)
, getBroadcast(Context, int, Intent, int)
, and getService(Context, int, Intent, int)
: if the described PendingIntent already exists, then keep it but its replace its extra data with what is in this new Intent. This can be used if you are creating intents where only the extras change, and don‘t care that any entities that received your previous PendingIntent will be able to launch it with your new extras even if they are not explicitly given to it.
Constant Value: 134217728 (0x08000000)