Using getCallingActivity():
If you start Activity with startActivityForResult
, the method can be used getCallingActivity().getClassName()
:
private void startRegistroActivity() {
Intent intent = new Intent(basecontext, Registro_Activity.class);
startActivityForResult(intent, 100);
}
And on 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 are already doing.
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 Activity:
Another option is to use objects that live longer than Activity, such as Singletons.
Declare the Singleton:
public enum ActivityReference {
INSTANCE;
Class<?> callingActivity;
public Class<?> getCallingActivity() {
return callingActivity;
}
public void setCallingActivity(Class<?> callingActivity) {
this.callingActivity = callingActivity;
}
}
Keep the value in it:
ActivityReference.INSTANCE.setCallingActivity(this.getClass());
Intent intent = new Intent(this, Activity.class);
startActivity(intent);
Access it at a later date:
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Class<?> callingActivity = ActivityReference.INSTANCE.getCallingActivity();
}
I believe putExtra is less costly for this case. Unless you have a very special reason to discard this solution.
– viana
@Viana My reason for trying to avoid, is that I don’t know yet how many activities will call this same Action, I think it would be more practical for me, to know where it comes from and to do the verification only in what I need. So if I ever decide to change all this, I will change only in the Ctivity that is being called, and I will not need to modify all the others that call for it. Do you understand?? I do not know if I explained well kkk
– Samanta Silva