android 工作室中 PendingIntent 中的请求代码是什么

What is the request code in PendingIntent in android studio

我正在尝试理解这段代码

Intent activityIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, activityIntent, 0);

我想了解 Pending Intent 中的那些参数 以及这些代码行的作用

请求代码是您在给定情况下选择的任意整数。通过意图创建 Activity 时,您可以检查请求代码的值以确定意图的来源。可能有几种情况会导致创建 Activity,请求代码是您区分的一种方式。

整数参数 requestCode 是一种区分具有相同操作、数据、类型、身份、class 和类别的多个意图的方法。否则,如果您使用相同的属性创建第二个意图,即使额外内容不同,它也不会起作用。

来自documentation

A PendingIntent itself is simply a reference to a token maintained by the system describing the original data used to retrieve it. This means that, even if its owning application's process is killed, the PendingIntent itself will remain usable from other processes that have been given it. If the creating application later re-retrieves the same kind of PendingIntent (same operation, same Intent action, data, categories, and components, and same flags), it will receive a PendingIntent representing the same token if that is still valid, and can thus call cancel() to remove it.

Because of this behavior, it is important to know when two Intents are considered to be the same for purposes of retrieving a PendingIntent. 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. The parts of the Intent that are used for matching are the same ones defined by Intent#filterEquals(Intent). If you use two Intent objects that are equivalent as per Intent#filterEquals(Intent), then you will get the same PendingIntent for both of them.

There are two typical ways to deal with this.

If you truly need multiple distinct PendingIntent objects active at the same time (such as to use as two notifications that are both shown at the same time), then you will need to ensure there is something that is different about them to associate them with different PendingIntents. This may be any of the Intent attributes considered by Intent#filterEquals(Intent), or different request code integers supplied to getActivity(Context, int, Intent, int), getActivities(Context, int, Intent[], int), getBroadcast(Context, int, Intent, int), or getService(Context, int, Intent, int).

顺便说一下,关于特定参数的文档,发件人的私人请求代码在我看来不是很有帮助。