Exit/Close android app programmatically on button click

How to force quit android application activity dynamically using button click event finish function.

Closing android application activity programmatically is very easy using finish() method. Finish method closet all the all open existing activities and exit application user. So in this tutorial we are exiting from MainActivity on button click method. So here is the complete step by step tutorial for Exit/Close android app programmatically on button click.

android-project-download-code-button

How to Exit/Close android app programmatically on button click.

Code for MainActivity.java file.

 package com.activityexitprogrammatically_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

 Button Quit;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 Quit = (Button)findViewById(R.id.button1);
 
 Quit.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 //Finish method is used to close all open activities.
 finish();
 
 }
 });
 }
}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.activityexitprogrammatically_android_examples.com.MainActivity" >

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text="Click here to Exit from Android Activity" />

</RelativeLayout>

Screenshots:

Click here to download Exit/Close android app programmatically on button click project.

Leave a Reply

Your email address will not be published. Required fields are marked *