0

I'm new to android.. I'm creating a sample app with 2 pages.. simply I want to exit my app if I press "back key" in android from any screen.. for ex: consider that I'm in page 2 and I'm pressing back key, now I want my app to exit rather than going to page 1.

Vijay
  • 1

5 Answers5

1

FYI .

At first add finish method when calling Intent

Intent intOBJ = new Intent(ActivityA.this, ActivityB.class);
startActivity(intOBJ );
finish();

Then goto ActivityB.class

Add this onBackPressed() method

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

finish()->Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().

IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
1

Each activity you have to override onBackPressed method. In this method you call a method name

this.finish(); or finish();

Community
  • 1
  • 1
faran.javed
  • 418
  • 2
  • 15
0

Each activity you have to override onBackPressed method.

Then you type

finishAffinity();    
System.exit(0);
Harry T.
  • 3,478
  • 2
  • 21
  • 41
  • 1
    do not use `System.exit(0)` in android – shinilms May 11 '17 at 06:21
  • @ShinilMS why not dude? – Harry T. May 11 '17 at 06:24
  • 2
    You should not call System.exit(). It could mess up Android's handling of the lifecycles of your activities and result in an awkward user-experience (e.g. when killing the process, the previous activity from which you launched your activity may be gone as well. Android may try to restart the process again and re-create that accidentally killed parent-activity) – shinilms May 11 '17 at 06:27
  • I have tried using finish() in activity 2; but it is taking me to activity 1.. but I want my app to exit.. – Vijay May 11 '17 at 06:31
  • @ShinilMS you was correct. – Harry T. May 11 '17 at 06:36
0

call finish(); after you start an intent from an activity.

eg:

Intent i = new Intent(ActivityA.this, ActivityB.class);
startActivity(i);
finish();
shinilms
  • 1,494
  • 3
  • 22
  • 35
0
@Override
public void onBackPressed() {
    android.os.Process.killProcess(android.os.Process.myPid());
    System.exit(1);
}