Using getCallingActivity ():
If you start Activity with startActivityForResult
, you can use the getCallingActivity().getClassName()
method:
private void startRegistroActivity() {
Intent intent = new Intent(basecontext, Registro_Activity.class);
startActivityForResult(intent, 100);
}
And in the second activity:
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
String className = getCallingActivity().getClassName();
}
Using Intents:
You can also use Intents as you already do.
At first Activity
:
Intent intent = new Intent(basecontext,Registro_Activity.class);
intent.putExtra("activity_name", this.getClass().getName());
startActivity(intent);
And in the second Activity
:
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
String className = getIntent().getStringExtra("activity_name");
}
Using Singletons or objects that live longer than the Activity:
Another option is to use objects that live longer than Activity, such as Singletons.
Declare Singleton:
public enum ActivityReference {
INSTANCE;
Class<?> callingActivity;
public Class<?> getCallingActivity() {
return callingActivity;
}
public void setCallingActivity(Class<?> callingActivity) {
this.callingActivity = callingActivity;
}
}
Save the value to it:
ActivityReference.INSTANCE.setCallingActivity(this.getClass());
Intent intent = new Intent(this, Activity.class);
startActivity(intent);
Access later:
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Class<?> callingActivity = ActivityReference.INSTANCE.getCallingActivity();
}