Nick
Nick

Reputation: 2641

Show Warning when user click on back button to Exit App

I was wondering how you would have a warning appear when the user tries to exit the app? So this includes if they are pressing the back button too. What would be the best way to do this?

I have seen this done on some mainstream games.

Upvotes: 3

Views: 3872

Answers (2)

Kalai.G
Kalai.G

Reputation: 1610

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    /*if (keyCode == KeyEvent.KEYCODE_HOME) {
        Log.i("Home Button", "Clicked");
        // Toast.makeText(this,"Home Button Clicked",Toast.LENGTH_LONG).show();
        return false;
    }*/  // You cannot gain control over home button

    if (keyCode == KeyEvent.KEYCODE_BACK) {
        Toast.makeText(this, "Press back Button to pause Evaluation",
                Toast.LENGTH_LONG).show();
        Log.i("Back Button", "Clicked");
        return false;
        // finish();
    }
    return false;
}

Upvotes: -1

lenik
lenik

Reputation: 23508

you may add onBackPressed() in your Application subclass to intercept the back button:

public static void onBackPressed(final Activity activity) {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle(R.string.on_back_button_title);
    builder.setMessage(R.string.on_back_button_message);
    builder.setPositiveButton(R.string.yes, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            activity.finish();
        }
    });
    builder.setNegativeButton(R.string.no, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    builder.show();
}

Upvotes: 7

Related Questions