Search code examples
androidandroid-intentandroid-pendingintent

How PendingIntent triggers intent?


For example, we have.

PendingIntent pi= PendingIntent.getActivity(context, requestCode, intent, FLAG);

When we pass our pi object to other class or other application, we know that intent wrapped in pi will be triggered later by that class or app Right?

I don't understand How it will be triggered?

When we use intent to start component manually/immediately, we call the method corresponding to exact component type (startActivity(intent), startService(intent), etc.) and as I know there is no such method like startAnyComponent(intent).

Thanks for your help.

P.S. I guess that there can be an easy way by checking Class objects when the intent is explicit

    Intent intent = new Intent(context, clazz):

In such case system can check if clazz.isAssignableFrom(Service.class) and call startService(intent).

But for implicit intents, I cannot realize what's going on.


Solution

  • When you get a PendingIntent, you call either getActivity(), getBroadcast() or getService(). When the PendingIntent is created, the type of Intent is included in the PendingIntent so that it knows if the Intent is for an Activity, BroadcastReceiver or Service.

    Later, when the PendingIntent is used, a call is made to get an IntentSender from the PendingIntent. To actually send the Intent, IntentSender.sendIntent() is called. The IntentSender knows how the PendingIntent was created and therefore knows whether it should use startActivity(), sendBroadcast() or startService() to properly send the Intent.

    NOTE:

    Regarding your assumption about how this could work using explicit Intents: This can't work, because usually the app that is actually sending the Intent doesn't have access to your app's code and therefore cannot load your classes and can't use Class.isAssignableFrom() to determine the type of Intent.