Go back to specific activity from stack

2019-02-21 17:22发布

问题:

I'm trying to do something like file manager. And in action bar I wanna to do folder navigation like in "google drive" app. I need create method which can go to previous activity by number from end, or something like this.

Example:

So if I have stack: [1] -> [2] -> [3] -> [4] -> [5]

And I need go to second: so I need delete [3], [4], and [5] from stack and go to [2].

All activities is one class ContentActivity.java.

How it possible to do?

UPDATE:

Some code how I start activities:

public class ContentActivity extends Activity implements AdapterView.OnItemClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        Intent intent = getIntent();
        String folderToOpen = intent.getStringExtra("folderName");
        fillList(folderToOpen);
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        ...
        Intent intent = new Intent(ContentList.this, ContentList.class);
        intent.putExtra("folderName", item.getName());
        startActivity(intent);
    }
}

回答1:

Assuming that Activity2 is the second activity that you want to go,

Try this:

Intent intent = new Intent(this,Activity2.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

According to Android Documentation about FLAG_ACTIVITY_CLEAR_TOP

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.



回答2:

Skip Activity by Manifest attribute

It depends from the need but if We simple want just skip activity in back flow, then helpful can be removing this activity from history in Manifest.

[1] -> [2] -> [3] - normal flow

[1] <- [3] - back flow

Then for [2] Activity We can in Manifest set noHistory attribute:

<activity
android:name=".SecondActivity"
android:noHistory="true" />

Thanks this approach our [2] Activity will never be launched in back flow.


Use Intent Flag

Removing activity from history stack is not always good idea, for example if our Activity sometimes need to be on back flow and sometimes not, then for launching wanted activity We need to set flag in intent:

Intent intent = new Intent(this, FirstActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

And very important - in FirstActivity manifest set launch mode on singleTop.

<activity
   android:name=".FirstActivity"
   android:launchMode="singleTop" />

Without launchMode attribute activity will be re-created.