Tutorial: Push to exit

23 November 2014 Written by 
Published in Android

Simple tutorial to make an exit double check in Android.

English

We will use the property isShown() from the class Toast to make a simplie exit check to avoid to close de application by a mistake.

Our first step is to add a Toast into our first Activity

 private Toast _exitToast;

and make an instance in OnCreate with the message to show, we can use the strings.xml file or directly a string

_exitToast = Toast.makeText(getApplicationContext(), "Push again to exit" , Toast.LENGTH_SHORT);

our last step is to add the override of onKeyDown, we will check is toast is visible in screen to exit with the next back button pulsation

push-to-exit2

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
        {
            if(_exitToast.getView().isShown())
            {
                //If it is the first activity it will exit
                _return super.onKeyDown(keyCode, event);
            }
            else
            {
                _exitToast.show();
            }
        }
        else
            return super.onKeyDown(keyCode, event);
        return false;
    }

Final full activity code:

package com.parallelcube.example;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

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

        _exitToast = Toast.makeText(getApplicationContext(), "Push again to exit" , Toast.LENGTH_SHORT);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
        {
            if(_exitToast.getView().isShown())
            {
                //si esta en el primer estado sale del programa
                return super.onKeyDown(keyCode, event);
            }
            else
            {
                _exitToast.show();
            }
        }
        else
            return super.onKeyDown(keyCode, event);
        return false;
    }
}

 push-to-exit

download
Download

Spanish

Utilizaremos la propiedad isShown() de la clase Toast para añadir una doble comprobación al salir para evitar que el usuario salga de la aplicacion por error.

Lo primero que tenemos que hacer es añadir un Toast a la primera Activity

 private Toast _exitToast;

y creamos la instancia del Toast en el metodo OnCreate con el mensaje a mostrar, podemos usar el strings.xml o directamente el string

_exitToast = Toast.makeText(getApplicationContext(), "Push again to exit" , Toast.LENGTH_SHORT);

por último añadimos el override del onKeyDown, comprobaremos que el Toast se esta mostrando en pantalla para salir con la siguiente pulsación del Back

push-to-exit2

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
        {
            if(_exitToast.getView().isShown())
            {
                //If it is the first activity it will exit
                _return super.onKeyDown(keyCode, event);
            }
            else
            {
                _exitToast.show();
            }
        }
        else
            return super.onKeyDown(keyCode, event);
        return false;
    }

El código de nuestra clase queda de la siguiente manera:

package com.parallelcube.example;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

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

        _exitToast = Toast.makeText(getApplicationContext(), "Push again to exit" , Toast.LENGTH_SHORT);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
        {
            if(_exitToast.getView().isShown())
            {
                //si esta en el primer estado sale del programa
                return super.onKeyDown(keyCode, event);
            }
            else
            {
                _exitToast.show();
            }
        }
        else
            return super.onKeyDown(keyCode, event);
        return false;
    }
}

 push-to-exit

download
Download
Read 1557 times Last modified on Sunday, 30 November 2014 11:23
More in this category: « Tutorial: Optimized listview
Login to post comments

We use cookies to ensure that we give you the best experience on our website. If you continue without changing your settings, we'll assume that you are happy to receive all cookies. View policy