Receive a call from any other activity

I am invoking an action from another action using this code:

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

and from my new action that starts with this code. I want to know what activity begins 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 cannot get the class name that triggers this action. I really need some help.

thanks

+4
source share
4 answers

There is a getCallingActivity() method, but this only works if the calling operation calls you using startActivityForResult() . I have seen libraries use this and say you should name them that way, but frankly, it's a little nasty. The simple answer: you should not know. Android is a system of loosely coupled actions, and the invoking activity should not make any real sense to your activity. Any information necessary for your activity should be clearly indicated in the intention, so if you really want to know who called you, the caller needs to add this additionally. You won’t be able to determine if they are lying, of course. Do not try to use this for anything related to security. However, I would suggest that everything you determine based on the caller is what the caller should pass on to you. Perhaps it is time to rethink why you want to do this, since trying to deal with the system will only lead to pain.

+11
source

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.

+2
source

It might be better to use the parameters of the additional parameters in the intent when you call them ... for example: Intent.putExtra (PARAM, value) on the activity of the caller ... and on the open operation that you are checking:

intent.getStringExtra (PARAM)

+1
source

getParentActivity () is not what you are looking for?

-2
source

All Articles