Chong Zheng Lun Chong Zheng Lun - 3 months ago 17
Android Question

Android exit whole program syntax

currently I'm working on Android development, now I'm facing a problem to exit the whole application that had launched.

I'v tried .finish(), but it doesn't show what I want.

I have 2 Activities, A and B. Activity A will forward to Activity B when button click. In activity B, when I click button "Exit" (that I created) with the listener to trigger .finish(), it just back to Activity A but not to close whole application (what I want is back to home screen directly and kill the background process as well).

How can I exit whole application wherever in the application? Thank you.

button.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {

//here to exit whole application not just backwards to previous activity
}

});

Answer

You write in Activity A after startActivity(new Intent(A.this, B.class)) finish() then you also write in Activity B finish() on button click listener. It should works.

public class A extends Activity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   Button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
             startActivity(new Intent(A.this, B.class));
             finish(); // you must write this also in A activity to close whole application
        }
    });
 }

    public class B extends Activity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_1);
   Button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
             finish();
        }
    });
 }
Comments