Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the sender of an Intent?

Tags:

android

Is there a way for an Activity to find out who (i.e. class name) has sent an Intent? I'm looking for a generic way for my Activity to respond to a received intent by sending one back to the sender, whoever that may be.

like image 991
zer0stimulus Avatar asked Jul 21 '10 22:07

zer0stimulus


4 Answers

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.

like image 115
Andy Zhang Avatar answered Nov 12 '22 07:11

Andy Zhang


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

like image 34
donfuxx Avatar answered Nov 12 '22 07:11

donfuxx


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,

like image 12
Mauricio Andrada Avatar answered Nov 12 '22 06:11

Mauricio Andrada


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.

like image 10
ajwillliams Avatar answered Nov 12 '22 05:11

ajwillliams