How to get the sender of an Intent?

Solution 1:

There may be another way, but the only solution I know of is having Activity A invoke Activity B via startActivityForResult(). Then Activity B can use getCallingActivity() to retrieve Activity A's identity.

Solution 2:

Is it an external app you receive the intent from? You could use the getReferrer() method of the activity class

A simple example: I opened google map app to share some location with my app by using the share option of google maps. Then my app opens and this method call in the Activity:

 this.getReferrer().getHost()

will return:

 com.google.android.apps.maps

see documentation here: https://developer.android.com/reference/android/app/Activity.html#getReferrer()

Note that this requires API 22. For older Android versions see answer from ajwillliams

Solution 3:

A technique I use is to require the application sending the relevant Intent to add a PendingIntent as a Parcelable extra; the PendingIntent can be of any type (service, broadcast, etc.). The only thing my service does is call PendingIntent.getCreatorUid() and getCreatorPackage(); this information is populated when the PendingIntent is created and cannot be forged by the app so I can get the info about an Intent's sender. Only caveat is that solution only works from Jellybean and later which is my case. Hope this helps,

Solution 4:

This isn't incredibly direct but you can get a list of the recent tasks from ActivityManager. So the caller would essentially be the task before yours and you can fetch info on that task.

Example usage:

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RecentTaskInfo> recentTasks = am.getRecentTasks(10000,ActivityManager.RECENT_WITH_EXCLUDED);

The above will return a list of all the tasks from most recent (yours) to the limit specified. See docs here for the type of info you can get from a RecentTaskInfo object.

Solution 5:

Generally you don't need to know this. If the calling activity uses startActivityForResult(Intent, int), the callee can use setResult(int, Intent) to specify an Intent to send back to the caller. The caller will receive this Intent in its onActivityResult(int, int, Intent) method.