How to Control Back Button in Android

How to Control Back Button in Android

There are various scenarios where we need to change the default functionality for our Back button. In this article, we are going to check all the scenarios and check how to code our back-button functionality.

Exit confirmation Scenario 1: In this scenario, we need to display a confirmation box. When user press back button and if it is the last activity of the app then show confirmation box.

Project Structure: We created a new project. Added an Empty activity.

java: MainActivity.java

layout: activity_main.xml

values: colors.xml, strings.xml, styles.xml

We don’t have anything special in our acitivy_main.xml file. Below is the code for activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.vlemonn.blog.confirmexit.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello vLemonn! Confirmation Box on Exit"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

In our MainActivity.java class, we override onBackPressed function. In onBackPressed function, we are displaying confirmation box. If user going to click on Yes then exit else ignore back press. Below is the final code for MainActivity.java class

package com.vlemonn.blog.confirmexit;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("Exit Demo App")
                .setMessage("Are you sure you want to exit?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //super.onBackPressed();
                        //Or used finish();
                        finish();
                    }

                })
                .setNegativeButton("No", null)
                .show();

    }
}

Below is the app output.

Confirm Exit on Android Back Pressed App OutPut

Confirm Exit on Android Back Pressed App OutPut[/caption]

Press Again for Exit Scenario 2: It is similar to Scenario 1. In this instead of an alert box, we are going to display a Toast message. When the user pressed back button again in short interval exit the app.

Project Structure: We created a new project. Added an Empty activity.

java: MainActivity.java

layout: activity_main.xml

values: colors.xml, strings.xml, styles.xml

We don’t have anything special in our acitivy_main.xml file. Below is the code for activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.vlemonn.blog.confirmexit.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello vLemonn! Press back twice to exit"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

In our MainActivity.java class, we override onBackPressed function. In onBackPressed function, we are using a boolean variable pressAgaintoExit.If pressAgaintoExit is false then set it to true and create new Runnable which reset pressAgaintoExit after one Second. One second is our short interval. If user press back again in short interval we are going to close the app. Below is the final code for MainActivity.java class.

package com.vlemonn.blog.confirmexit;

import android.content.DialogInterface;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    boolean pressAgaintoExit = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onBackPressed() {
        if(pressAgaintoExit)
        {
            super.onBackPressed();
            //Or finish();

        }
        else
        {
            pressAgaintoExit=true;
            Toast.makeText(this,"Press Back Again to Exit",Toast.LENGTH_SHORT).show();
            //Reset pressAgaintoExit after one second
            //So our short interval time is one second
        /* 1000 One Second time Make it 2000 for 2 Seconds*/
            int intervalTime = 1000;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    pressAgaintoExit = false;
                }
            },intervalTime);
        }



    }
}

 

WebView Scenario 3: In this scenario, we are using a WebView. We need to exit app if WebView Back History is finished.

Project Structure: We created a new project. Added an Empty activity.

java: MainActivity.java

layout: activity_main.xml

values: colors.xml, strings.xml, styles.xml

The first and most important thing we need Internet access for this app. Add below line in our AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

In our activity_main.xml file we have a WebView. Below is the code for activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.vlemonn.blog.confirmexit.MainActivity">

    <WebView
        android:id="@+id/webView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

In our MainActivity.java class, we added a code to control webview. Finally, we override onBackPressed function. In onBackPressed function we have a check for webView.canGoBack(). If webView.canGoBack() returns true we need to go back in web view history.If the return value is false then we need to close our activity. Below is the final code for MainActivity.java class.

package com.vlemonn.blog.confirmexit;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    WebView webView;
    String url="https://vLemonn.com";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView) findViewById(R.id.webView);
        webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
            }
        });
        webView.setWebViewClient(new MyWebViewClient());
        WebSettings browserSetting = webView.getSettings();
        browserSetting.setJavaScriptEnabled(true);
        webView.loadUrl(url);
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    }

    @Override
    public void onBackPressed() {
        if(webView.canGoBack())
        {
            webView.goBack();
        }
        else
        {
            super.onBackPressed();
        }
    }
}

 

Android Drawer Scenario 4: In this scenario, we are going to handle android navigation drawer.

Project Structure: We created a new project. Added an Android Navigation Drawer Activity.

java: MainActivity.java

layout: activity_main.xml, app_bar_main.xml, content_main.xml, nav_header_manin.xml

values: colors.xml, strings.xml, styles.xml

We don’t modify any thing in the default project files. Now it’s time to understand the code for onBackPressedFunction. Below is the code for onBackPressed function.

@Override
    public void onBackPressed() {
        //Initialised the drawer
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        //Check drawer state. If it is open close it first.
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

 

This time the default body of onBackPressed function is different as compare to previous scenarios. This time we have some extra line of code to handle Android Navigation Drawer.

The first line is initializing the navigation drawer.

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

Then we have check if Android drawer is opened close the drawer first and ignore the back press. If drawer is not open use super.onBackPressed();

Let’s run our app.

Save Data Before Exit Scenario 5: In this scenario, we have a profile page. We need to check if we have any unsaved changes save it first then exit.

Project Structure: We created a new project. Added an Empty Activity.

java: MainActivity.java

layout: activity_main.xml

values: colors.xml, strings.xml, styles.xml

We add an EditText with default value http://vlemonn.com for our WebSite URL input. Below is the final code for activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.vlemonn.java.blog.confirmexit.MainActivity">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="http://vlemonn.com"
        android:id="@+id/etWebSite"
        android:hint="vLemonn Website"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Now in our MainActivity.java class, we are initializing the EditText. We created a new instance of TextWatcher and assign it to our EditText. When we are changing anything in EditText and it is not equal to the default value then we have some unsaved changes. When we have some unsaved changes we are displaying the Toast message and ignoring the back pressed event. Below is the code for MainActivity.java class

package com.vlemonn.java.blog.confirmexit;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    EditText etWebSite;
    boolean newChanges=false;
    String oldSavedValue = "http://vlemonn.com";
    String newValue="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etWebSite = (EditText) findViewById(R.id.etWebSite);

        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                newValue = etWebSite.getText().toString();

                if(newValue.equals(oldSavedValue))
                {
                    newChanges=false;
                }
                else {
                    newChanges=true;
                }

            }

            @Override
            public void afterTextChanged(Editable s) {


            }
        };
        etWebSite.addTextChangedListener(textWatcher);
    }

    @Override
    public void onBackPressed() {
        if(newChanges)
        {
            Toast.makeText(this,"You have some un saved changes."
                    +" Please save it and try again to exit the app.",Toast.LENGTH_LONG).show();
        }
        else
        {
            super.onBackPressed();
        }
    }
}

 

Finally, it’s time to launch our Android app

 

Disable on Back Pressed Scenario 5: When we have our custom Exit Button then we can use this scenario. For disabling the back pressed we are going to override the onBackPressed function. In the override function body, we are going to remove the below line to disable onBackPressed.

super.onBackPressed();
0 Comments
Leave A Comment

Please login to post your valuable comments.

Join the newsletter

Get the latest vLemonn news first

share