Search code examples
androidandroid-activitystackback

A way of knowing what activity will be launched when BACK is pressed in Android


I need to know if there is any way to know when on an Activity what is the Activity that will be opened when the back button is pressed. I suppose i can take a look at the activity stack but i need some pointer on how to do it.

Thanks in advance.

EDIT: Thank for all the answers but i still want to explain the real problem.

I have an App that has a bunch of activities that consume a lot of power (sensor, gps and wifi), that i want to keep quiet when i'm not using that 'Task' (i.e going to do something else).

How can i trap the event of not having nothing more of my application in the back-stack?


Solution

  • Send along an intent extra from ActivityX to ActivityY. The extra could be a reference to a constant value which identifies an activity.

    ActivityX:

    startActivity(new Intent(context, ActivityY.class).putExtra("fromActivity", Const.EXTRA_FROM_ACTIVITY_X));

    ActivityYB:

    private int fromActivity;
    public void onCreate(Bundle savedInstanceState) {
        ...
            fromActivity = getIntent().getExtras().getInt("fromActivity");
        ...
    }
    public void onBackPressed() {
        switch(fromActivity) {
            case Const.EXTRA_FROM_ACTIVITY_X:
                //we are going back to ActivityX
                break;
        }
    }
    

    Where Const is a class holding unique static final int variables such as EXTRA_FROM_ACTIVITY_X