Search code examples
androiduriactivity-stack

Android - How to get Activity path


How can i get the path the end user takes to arrive at any activity.

so if user visited Activities A, B , C .. then in Activity c i would be able to get a info like this "A/B/C". And likewise if user took the path directly to D, F then in activity F i would have the path info of "D/F".


Solution

  • Whenever you start an Activity you could pass it a string extra that states the path you're talking about. A quick example could be to have this method in an abstract base activity class and use it whenever starting a new Activity:

    public <T extends Activity> void startActivityWithPathInfo(Class<T> activityClass) {
        String path = getIntent().getStringExtra("path");
        path = path == null ? "" : path += "/";
        path += this.getClass().getSimpleName();
        Intent i = new Intent(this, activityClass);
        i.putExtra("path", path);
        startActivity(i);
    }
    

    Then in each activity you could just get the current path by using:

    String path = getIntent().getStringExtra("path");
    

    Edit: Given your requirements, it's probably better to split this up into a "getPath()" method and a "startActivityWithPathInfo(Class)" method. Might be easier for you to retrieve the path in each Activity :)

    Edit 2: As per comments, here is the updated code:

    public abstract BaseActivity extends Activity {
        private static final String EXTRA_PATH = "path";
    
        private String path;
    
        @Override public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (savedInstanceState == null) {
                path = getPath();
            } else {
                path = savedInstanceState.getString(EXTRA_PATH, "");
            }
        }
    
        @Override protected void onSaveInstanceState(Bundle outState) {
             super.onSaveInstanceState(outState);
             outState.putString(EXTRA_PATH, path);
        }
    
        public String getPath() {
            if (path == null) {
                path = getIntent().getStringExtra(EXTRA_PATH);
                path = path == null ? "" : path += "/";
                path += this.getClass().getSimpleName();
            }
            return path;
        }
    
        public <T extends Activity> void startActivityWithPathInfo(Class<T> activityClass) {
            Intent i = new Intent(this, activityClass);
            i.putExtra(EXTRA_PATH, getPath());
            startActivity(i);
        }
    }