Possible Duplicate:
Android: How to get the sender of an Intent?
Is there a way in android to find the source activity which fires a INTENT (in the destination activity)?
The scenario is I have two activities A and B. Both fire an intent to call activity C. Activity C displays extra information based on its source. Eg. If call comes from A then C displays only 2 textviews whereas in the case of intent fired by B the activity C displays 3 textviews (basically more information based on who is the caller).
To establish this I need to know who fired the intent calling C. How do I do this?
A better way to do this would be to use Intent extras to pass parameters to the receiver.
If we look at the Intent.java class, we can see the members only included
private String mAction;
private Uri mData;
private String mType;
private String mPackage;
private ComponentName mComponent;
private int mFlags;
private HashSet<String> mCategories;
private Bundle mExtras;
I do not think any of these members include sender information, making the answer to the question no. You couldn't do this for an arbitrary intent.
Might this be considered a workaround?
Have A & B call startActivityForResult
instead of startActivity
, then you can call getCallingActivity().getClassName()
to retrieve the source.
If app C has the GET_TASKS permission, you can see what the most recent task was.
ActivityManager man = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RecentTaskInfo> list = man.getRecentTasks(1, 0);
//You might want to check if(list.size() > 0)
Intent caller = list.get(0).baseIntent;
//look at caller.getComponent() for the package and class
In my testing, I found that baseIntent on the top of the recent task stack was the most reliable identifier. There is more discussion about why you might not want to do this in https://stackoverflow.com/a/12376775/1135142
I suppose if you have any control over A and B, you could have them call for a result as mentioned already.
精彩评论