Farrukh
Farrukh

Reputation: 279

Get calling activity from some other activity

I am calling an activity from another activity by this code:

Intent intent = new Intent(context, mClass);
context.startActivity(intent);

and from my new activity which is started by this code. I want to know which activity starts this activity. I used this code for this purpose

Intent intent = getIntent();
Class<?> c = intent.getClass();
if (c != OffersActivity.class) {
    prepareForNotifications();
    setListAdapter();
}

but by this code I am not able to get the classname which starts this activity. I really need some help.

thanks

Upvotes: 7

Views: 18313

Answers (4)

themightyjon
themightyjon

Reputation: 1436

There is a method getCallingActivity(), but that only works, if the calling activity calls you with startActivityForResult(). I have seen libraries use that and say that you must call them that way, but frankly it is a bit nasty. The simple answer is that you're not supposed to know. Android is a system of loosely coupled activities and the calling activity should thus have no real meaning to your activity. Any information your activity needs should be put explicitly in the intent, so if you really want to know who called you then the caller needs to put that extra in. You won't be able to tell if they are lying of course, so don't go trying to use this for anything security-related. However, I would suggest that whatever you're determining based on the caller, is what the caller should be passing you instead. Might be time for a rethink on why you want to do this, since trying to fight the system will only lead to pain.

Upvotes: 12

Thomas Decaux
Thomas Decaux

Reputation: 22671

getParentActivity() is not what yout are looking for?

Upvotes: -2

stealthjong
stealthjong

Reputation: 11093

I would suggest:

public static final String INTENTSENDER = "sender";

void mMethod() {
    Intent intent = new Intent(context, mClass);
    intent.putExtra(INTENTSENDER, mClass);
    context.startActivity(intent);
}

knowing who sent it:

Class<?> c = (Class<?>)intent.getExtras().get(INTENTSENDER);

However, you can also use this:

ComponentName componentName = this.getCallingActivity();

Now, you can use componentName to get the sender of the intent.

Upvotes: 2

Al&#233;cio Carvalho
Al&#233;cio Carvalho

Reputation: 13657

Maybe it's best to use the extras parameters in the intent when you call them...like: Intent.putExtra(PARAM,value) on the caller activity...and on the opened activity you check:

intent.getStringExtra(PARAM)

Upvotes: 1

Related Questions