Press Double Click To Exit App in Android Example |Android App Development With AndroidCource

Saturday, 23 June 2018

Press Double Click To Exit App in Android Example


Double Press To Exit in Application to implement onBackPress Event in Activity Lifecycle and maintain to back button in your device to press one click to show Toast message and before retry to click to another 2 second to show toast in single click.when click double press back button to exit this app and does not show Toast when Exited to app screen.

MainActivity.xml

<?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=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

MainActivity.java

package com.example.com.doublebacktoexitapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    public long doubleclick;
    public Toast backToast;

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

    }

    @Override
    public void onBackPressed() {

        if(doubleclick + 2000 > System.currentTimeMillis()){
            backToast.cancel();
            super.onBackPressed();
            return;
        }else{
            backToast = Toast.makeText(MainActivity.this,"Press Back Again To Exit",Toast.LENGTH_SHORT);
            backToast.show();
        }
        doubleclick = System.currentTimeMillis();

    }
}


0 comments:

Post a Comment