Abhishek Dwivedi
Abhishek Dwivedi

Reputation: 7416

Android - disabling back and home button

How to disable back and home button in Android application. So that my application will not close by tapping on the back or home buttons.

Upvotes: 0

Views: 130

Answers (2)

Abhishek Dwivedi
Abhishek Dwivedi

Reputation: 7416

By default, back key and home key tap events are handled at android framework. If we want to change the behavior of these two soft buttons we need to handle this in our application activity.
Following is the code snippet showing a simple code for keeping current activity in front even upon the back or home softkey tap.

public class MyActivity extends AppCompatActivity {

// .. Other codes ...
//....
    @Override
    protected void onPause() {

       super.onPause();
       ActivityManager activityManager = (ActivityManager) getApplicationContext()
            .getSystemService(Context.ACTIVITY_SERVICE);
       activityManager.moveTaskToFront(getTaskId(), 0);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
       return true;
    }

    @Override
    public void onBackPressed() {}

}

See here overriding. Also add REORDER_TASKS permission in AndroidManifest.xml

AndroidManifest.xml

<uses-permission android:name="android.permission.REORDER_TASKS" />

Upvotes: 0

Farhana Naaz Ansari
Farhana Naaz Ansari

Reputation: 7928

override the back pressed method and leave it blank.

When you create onBackPressed() just remove super.onBackPressed(); and that should work

 override fun onBackPressed() {


}

Upvotes: 1

Related Questions