C
C
Chvalov2014-12-17 13:25:58
Java
Chvalov, 2014-12-17 13:25:58

How to prevent quitting an app with the back button in Android?

Hello, the tablet is Android 5.0.1 (Asus TF300T)
I need to disable the exit from the application with the back key, I work in the Android Studin 1.0.1 environment. I put
all the code along the path Project-> java-> com.test.project-.MainActivity
Code

@Override
public void onBackPressed()
{
     moveTaskToBack(true);
}
Does not work
@Override
public void onBackPressed()
{
     super.onBackPressed();
}
Also doesn't work.
Tell me how to do this, or am I not writing code there at all?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Appp Zooo, 2014-12-17
@Chvalov

Working and final version:

@Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      return true;
    }
    return false;
  }

The old code was written back in the 12th (for folding instead of closing), but it worked:
// Don't close application
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      moveTaskToBack(true);
      return true;
    }
    return false;
  }

or else found this:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    return false;
}

@Override 
public void onBackPressed(){  
   Toast.MakeText(getApplicationContext(),"You Are Not Allowed to Exit the App",     Toast.LENGTH_SHORT).show();
}

C
Chvalov, 2014-12-18
@Chvalov

Something I didn’t understand at all
Here is the code that is responsible for pressing the back key

@Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      return true;
    }
    return false;
  }
And here is the code which, as I understand it, returns false on any keystroke
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    return false;
}
But it works exactly the same as the upper code, everything else works (Folding, etc.) how to understand this?
As I understand it, there I would have to specify the key and its behavior
developer.android.com/reference/android/view/KeyEv...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question