Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to finish all activities and close the application in android?

My application has the following flow:

Home->screen 1->screen 2->screen 3->screen 4->screen 5>Home->screen 2->Home->Screen 3

My problem is that when I am trying to close the application then Home activity opens everytime when I am trying to close the application.

I just want to close the application when user presses the back key of device on home screen.

like image 290
rahul Avatar asked Nov 26 '13 07:11

rahul


4 Answers

There is finishAffinity() method that will finish the current activity and all parent activities, but it works only in Android 4.1 or higher.

like image 133
Ragaisis Avatar answered Nov 14 '22 22:11

Ragaisis


This works well for me.

  • You should using FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK flags.

    Intent intent = new Intent(SecondActivity.this, CloseActivity.class);
    //Clear all activities and start new task
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); 
    startActivity(intent);
    
  • onCreate() method of CloseActivity activity.

    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        finish(); // Exit 
    }
    
like image 32
Loi Ho Avatar answered Nov 14 '22 21:11

Loi Ho


Use finishAffinity() method that will finish the current activity and all parent activities. But it works only for API 16+ mean Android 4.1 or higher.

API 16+ use:

finishAffinity();

Below API 16 use:

ActivityCompat.finishAffinity(this); //with v4 support library

To exit whole app:

finishAffinity(); // Close all activites
System.exit(0);  // Releasing resources
like image 24
Sheikh Hasib Avatar answered Nov 14 '22 22:11

Sheikh Hasib


Sometime finish() not working

I have solved that issue with

finishAffinity()

Do not use

System.exit(0);

It will finish app without annimation.

like image 34
AJay Avatar answered Nov 14 '22 21:11

AJay