Disable back button in android

2018-12-31 10:14发布

How to disable back button in android while logging out the application?

14条回答
呛了眼睛熬了心
2楼-- · 2018-12-31 10:49

Just using this code: If you want backpressed disable, you dont use super.OnBackPressed();

@Override
public void onBackPressed() {

}
查看更多
浮光初槿花落
3楼-- · 2018-12-31 10:50

If you want to make sure your android client application is logged out from some server before your Activity gets killed --> log out with a service on its own thread (that's what you're supposed to do anyway).

Disabling the back button won't solve anything for you. You'll still have the same problem when the user receives a phone call for instance. When a phone call is received, your activity has about as much chances of getting killed before it gets a reliable answer back from the network.

That's why you should let a service wait on its own thread for the answer from the network, and then make it try again if it doesn't succeed. The android service is not only much less likely to get killed before it gets an answer back, but should it really get killed before finishing the job, it can always get revived by AlarmManager to try again.

查看更多
琉璃瓶的回忆
4楼-- · 2018-12-31 10:50

Apart form these two methods from answer above.

onBackPressed() (API Level 5, Android 2.0)

onKeyDown() (API Level 1, Android 1.0)

You can also override the dispatchKeyEvent()(API Level 1, Android 1.0) like this,

dispatchKeyEvent() (API Level 1, Android 1.0)

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    // TODO Auto-generated method stub
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
        return true;
    }
    return super.dispatchKeyEvent(event);
}
查看更多
步步皆殇っ
5楼-- · 2018-12-31 10:51

For me just overriding onBackPressed() did not work but explicit pointing which activity it should start worked well:

@Override
public void onBackPressed(){
  Intent intent = new Intent(this, ActivityYouWanToGoBack.class);
  startActivity(intent);
}
查看更多
与风俱净
6楼-- · 2018-12-31 10:53

If looking for android api level upto 1.6.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
     if (keyCode == KeyEvent.KEYCODE_BACK) {
     //preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
     return true;
     }
     return super.onKeyDown(keyCode, event);    
}

And if looking for a higher api level 2.0 and above this will work great

@Override
public void onBackPressed() {
    // Do Here what ever you want do on back press;
}

write this code in your Activity to prevent back button pressed

查看更多
路过你的时光
7楼-- · 2018-12-31 10:53

You can do this simple way Don't call super.onBackPressed()

Note:- Don't do this unless and until you have strong reason to do it.

@Override
public void onBackPressed() {
    super.onBackPressed();
// dont call **super**, if u want disable back button in current screen.
}
查看更多
登录 后发表回答