How do I know what previous activity the current activity was called?

7

I have several Activities, which can call a special Activity.

I would like to know how to identify which activity you called.

It would be something like this:

IneedthisbecauseIhaveauserregistrationactivity,whichcanbecalledthroughseveralplacesinmyapplication.ButIneedtoknowwhatplaceitwascalled,becausedependingonwhocalledititshouldperformanaction.

Ithoughtofdoingso:

Intentintent=newIntent(basecontext,Registro_Activity.class);intent.putExtra("ACTIVITYPAI", "ACTIVITY-A");
startActivity(intent);

And put this on every screen you call. But if you have a way of not needing to use putExtra, and the logging activity itself identifies where it came from, it would be best for me.

    
asked by anonymous 23.05.2018 / 10:15

1 answer

5

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();
}
    
23.05.2018 / 13:04