Skip to main content

[Android Tutorial] Press back button twice to exit app

Few Apps have the feature to close the app when back button is pressed twice. This feature comes handy when there is accidental press of back button. This feature allows the user to close the app only when back button is pressed twice.

Today we will be showing you how to implement this on your own app.

We will be using a custom toast to demonstrate this features. But you may want to try this on default toast settings too.

We will be using this on the MainActivity.java file but you may want to use accordingly to any class file. Preferred is the home activity file.

Step 1 Create a variable of integer type and assign its value to 0.
Ex - int count = 0;
Step 2 Create a method onBackPressed() to  override the default back settings.

Paste the following code -

public void onBackPressed()
{
    if(count == 1)
    {
        count=0;
        finish();
    }
    else    {
        
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.custom_toast,
                (ViewGroup) findViewById(R.id.custom_toast_container));

        TextView text = (TextView) layout.findViewById(R.id.text);
        text.setText("Press Back again to Exit");

        final Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.BOTTOM, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override            public void run() {
                toast.cancel();
            }
        }, 800);
        count++;
    }

    return;
}



Step 3 Create a new .xml file named custom_toast.xml inside the res/layout/ directory.
Paste the following code - 
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/custom_toast_container"    android:orientation="horizontal"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:padding="8dp"    android:background="#FFF"    >
    <ImageView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginRight="8dp"        tools:ignore="ContentDescription,RtlHardcoded" />
    <TextView android:id="@+id/text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textColor="#FF4C4C"        />
</LinearLayout>


Step 4 Now run the app it should work perfectly.
Step 5 Enjoy! profit.
Screenshots:-

Comments

Popular posts from this blog

[TechLeaks] Moto X4 image leaks showing off glass back, dual camera, thin side bezels

Update: The first image of the Moto X4 has leaked (see above). It was recently posted on Twitter by Evan Blass and shows the front as well as the back of the upcoming smartphone. The device looks a lot like the rest of the Moto lineup with its large circular camera housing on the rear and the fingerprint scanner positioned on the front, below the screen. The image shows the gold version of the Moto X4, although we do expect to see it in a few other color options once it’s officially released. One of the smartphones we’re really looking forward to from Motorola this year isn’t a refresh to the Moto Z , but rather the return of the Moto X lineup in the Moto X4. With specs and rumors flying around, Evan Blass has taken to Twitter to share the first good look at the upcoming device. The latest addition to the Moto X lineup, the Moto X4, is expected to be a return to the Motorola that once got us excited , at least to an extent. Whereas the Moto Z line focuses on premium sp...

[Phone Launch] Xiaomi launches its first Android One smartphone named Mi A1

Xiaomi unveiled the Mi A1 earlier today in New Delhi, and the phone marks a shift in strategy for the manufacturer. While all Xiaomi phones thus far have featured MIUI, the Mi A1 offers stock Android. The phone is the first in a new lineup of Android One devices, with Google looking to aggressively target the budget segment in emerging markets. The highlight of the Mi A1 is its dual camera setup at the back with a 12 MP wide-angle and a 12 MP telephoto lens. The 50 mm telephoto lens captures the main image and the wide-angle lens assists with the depth of field measurement, and the two lenses work together to create a bokeh. The telephoto lens enables up to 2x optical zoom and for even further shots, Mi A1 offers up to 10x digital zoom. Also, like the Pixel and Pixel XL by Google in the past, the Mi A1 offers unlimited high-quality photo storage on Google Photos. Xiaomi Mi A1 Specifications Operating System Android 7.1.2 Nougat Display 5.5-inch IPS LCD 192...

[Tech News] Google Chrome Canary and Dev Builds now have Built-In Ad Blocker

Google depends on advertising for its revenue. It is to serve this purpose that the company collects all relevant data across all of its users. Our browsing habits, our shopping-related searches, our weekly schedule — all of these are of interest to Google because they grant an insight into our lives, allowing Google to serve personalized ads that have a higher chance to resonate with viewers. So earlier this year, when reports emerged that Google was looking to incorporate an ad blocker in Google Chrome  – its main browser that serves millions of Android users – many people were initially surprised. After all, ads are Google’s forte, so blocking them natively seems like a strange idea. However, the reports clarified that even though the ad blocker would be turned on by default, it will only block out those specific types of ads that are deemed too intrusive and that negatively affect a user’s browsing experience. Some users on Google Chrome’s Canary and...