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
Start the Second Activity To start an activity, call startActivity() and pass it your Intent . The system receives this call and starts an instance of the Activity specified by the Intent . Now you need to create the DisplayMessageActivity class in order for this to work.
We can send the data using the putExtra() method from one activity and get the data from the second activity using the getStringExtra() method.
MainActivity.java onCreate(savedInstanceState); setContentView(R. layout. activity_main); instance = this; } public static MainActivity getInstance() { return instance; } public void myMethod() { // do something... } )
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With