-2

I have three activities: First, Second and Third. I used this method in Second activity:

public void onBackPressed() {
    super.onBackPressed();
    finish();
}

and this on Third activity:

public void onBackPressed() {
    super.onBackPressed();
    Intent i = new Intent(Third.this, Second.class);
    startActivity(i);
    finish();
}

The problem is when I press back button after coming from the Third activity, I am going into First activity instead of finish(). I am successfully exiting the application when I click back button right after coming from first activity but not after coming from Third activity.

How to solve this problem?

EDIT: Thanks for the answers guys,the answer of "Ved Prakash" solved the problem for me.But i have a weird problem now.When i press back button the app is successfully exiting but the app which i minimized to Recent Apps button is coming on to the screen and exiting.For example,if i have opened Setting app before opening my app,when i press back button,my app is exiting and immediately Settings app is also opening and exiting itself.What might be the problem?

Ramu
  • 123
  • 8
  • Please add a tag indicating what language you're using. – Tom Zych Jun 23 '14 at 09:11
  • I don't understand what are you expecting and what you get. Your onBackPressed in second activity does't do anything. super.onBackPressed() will close current activity and finish do the same. – Alexander Mikhaylov Jun 23 '14 at 09:15
  • super.onBackPressed() calls finish() naturally... that's what it does. It kills the current activity. If you want to switch around and kill the app even from the third activity, then you should probably switch to fragments and just not use the "addToBackStack(null)" method on the replace. – EpicPandaForce Jun 23 '14 at 09:30

4 Answers4

1

Your problem is that you don't seem to understand how Activities work. The finish() function ends the current Activity, and then you receive the previous Activity from the backstack.

My recommendation is that you should use a single Activity, and hold Fragments inside it. If you want it so that pressing the Back button ends the application at any screen that is displayed, you could do the following:

Activity XML:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/initial_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Activity that holds the Fragments:

public class InitialActivity extends FragmentActivity implements ReplaceWith
{

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

        getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener()
        {
            public void onBackStackChanged()
            {
                int backCount = getSupportFragmentManager().getBackStackEntryCount();
                if (backCount == 0)
                {
                    finish();
                }
            }
        });

        if (savedInstanceState == null)
        {
            getSupportFragmentManager().beginTransaction().add(R.id.initial_container, new FirstFragment()).commit();
        }
    }

    @Override
    public void replaceWith(Fragment fragment)
    {
        getSupportFragmentManager().beginTransaction().replace(R.id.initial_container, fragment).commit();
    }
} 

Example for a Fragment:

public class FirstFragment extends Fragment implements View.OnClickListener
{
    private ReplaceWith activity_replaceWith;

    private ImageView exampleImage;

    public FirstFragment()
    {
        super();
    }

    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);
        try
        {
            activity_replaceWith = (ReplaceWith) activity;
        }
        catch (ClassCastException e)
        {
            Log.e(getClass().getSimpleName(), "Activity of " + getClass().getSimpleName() + "must implement ReplaceWith interface!", e);
            throw e;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_first, container, false);
        exampleImage = (ImageView) rootView.findViewById(R.id.fragment_first_example_image);
        exampleImage.setOnClickListener(this);
        return rootView;
    }

    @Override
    public void onClick(View v)
    {
        if(v == exampleImage)
        {
            activity_replaceWith.replaceWith(new SecondFragment());
                //please note that this should be done only if you are planning
                //only on single-screen applications 
                //with no other layouts based on orientation or size
                //otherwise, the Activity needs to be responsible for this, not the Fragment
        }

    }
}

This way, when you press the Back button, your application would end from any displayed screen.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • The reason why the application would end is because the Fragments aren't put into the backstack. If you needed it so that the Back button returns to the previous Fragment, call the addToBackStack(null) before the commit(). – EpicPandaForce Jun 23 '14 at 09:41
0

Ok your code is wrong. If you will look at activity source, you see that activity.onBackPressed() is calling finish(). So if call super.onBackPressed() you don't need to call finish. Finish() is not stopping your application, it's stopping current activity. Your code on third activity very strange. You are trying to stop activity and start another same activity. What exactly you want to achieve?

If you want to exit application from your third activity, you need to clear your backstack. But I think you have problem with structure of your app.

Alexander Mikhaylov
  • 1,790
  • 1
  • 13
  • 23
  • Thanks for the explanation.Actually my first activity is a login activity,ad when i login i will get the second activity.So i should not get this first (login)activity when i press back in second activity.I did call finish() in first activity and it works after going to second activity.But when i go to the third activity and come back again to second activity and click back button,i am going to the first(login) activity again. – Ramu Jun 23 '14 at 09:41
  • @Ramu You don't need to override onBackPressed in this case. You only need to set flag "noHistory" of your login activity. Look here http://developer.android.com/guide/topics/manifest/activity-element.html. And you will never return to login activity with back button. – Alexander Mikhaylov Jun 24 '14 at 06:34
0

Ok. then you should finish your first activity when you go to second activity like this(If you are using intent for that):

Intent it=new Intent(FirstActivity.this,SecondActivity.class);
finish();
startactivity(it);

and same for Second Activity:

 Intent it=new Intent(SecondActivity.this,ThirdActivity.class);
 finish();
 startactivity(it);

this done your work...when you are in third activity the above activities are finished.. and when you press backButton you will be exit from application.. Good luck.

WonderSoftwares
  • 2,800
  • 1
  • 15
  • 21
0

You can use -

public static final int 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.

And here is how -

When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "MainActivity".

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.

  if (getIntent().getBooleanExtra("EXIT", false)) {
        finish();
    }

This explanation part is also introduced at exit-an-android-app.

Community
  • 1
  • 1
sjain
  • 23,126
  • 28
  • 107
  • 185
  • Thanks for the answer,it worked perfectly.But i have a weird problem now.When i press back button the app is successfully exiting but the app which i minimized to Recent Apps button is coming on to the screen and exiting.For example,if i have opened Setting app before opening my app,when i press back button,my app is exiting and immediately Settings app is also opening and exiting itself.What might be the problem?I hope you understand what i am trying to say. – Ramu Jun 23 '14 at 10:12
  • Don't know if I understood what you said. There is no relation of any other app with this code. The code is as simple as clearing all activities from stack and then calling finish from starter activity to exit the application. – sjain Jun 23 '14 at 10:33