3

I'm installing my app then save data using Main Activity and going to another Fragment activity.Next time I'm starting my App always preview second Fragment then I press back going to Main Activity But I don't want to go Main Activity.I want press back button close My App.I try this

@Override
public void onResume() {
    super.onResume();

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                // handle back button's click listener
                Toast.makeText(getActivity(), "Back press", Toast.LENGTH_SHORT).show();
                return true;
            }
            return false;
        }
    });

}
amila isura
  • 1,050
  • 1
  • 16
  • 26

6 Answers6

3

in your Mainactivity, after the line startActivity() for starting second activity add this line this.finish();

Deepak John
  • 967
  • 1
  • 7
  • 19
1

try some like this in your onBackPress method

@Override
    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        //to clear all old opened activities 
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }
Kristiyan Varbanov
  • 2,439
  • 2
  • 17
  • 37
0

--Simplest way to close/exit app :

@Override
    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }
Nik Patel
  • 627
  • 7
  • 21
0

Try this :

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
       }
vabhi vab
  • 419
  • 4
  • 11
0

I believe this thread can help you: Android: Quit application when press back button

Let's say your Main Activity is B and the Fragment activity is A. Then, you must clear the stack of activities and leave only A on the stack. Use this:

Intent launchNextActivity;
launchNextActivity = new Intent(B.class, A.class);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);                  
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(launchNextActivity);
Community
  • 1
  • 1
HuyTranQ
  • 1
  • 1
0

override onBackPressed method in your main activity

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

ashwini
  • 142
  • 8