I'm trying to close my app on a back button click. From the main screen, the back button takes you to a credits screen. From that credits screen, I want to close the app with the back button. Unfortunately, the onBackPressed() method I'm calling doesn't seem to be executed at all. I'm not sure how to proceed.
package app.jonward.boss;
import android.app.Activity;
public class Credits extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.credits);
//Doing stuff
}
@Override
public void onBackPressed() {
finish();
return;
}
}
I don't get it. What onBackPressed()
does is to call finish()
. finish()
is an Activity
method, there's no way to "quit" your app, so to speak. Perhaps what you really want is to call finish()
on the Activity that is starting the Credits
activity. Inside the other activity:
finish();
startActivity(this, Credits.class);
Try the following solution?
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
Just recently, i ran into this issue and i was able to solve it by deleting all the folders in the build
directory.
I don't know how but it seemed that Android Studio
made an error generating the build and that lead to this problem. So after deleting the build
directory, myonBackpressed()
method was being called.
Sorry, i am not able to comment yet (I wanted this to be a comment on Muffinbubble's answer)..
Try putting the onKeyDown into your mainclass and validate if this get's called even if you are in your second Activity. You could then check where you are via the main class and exit the application if needed and else return super.onKeyDown(..).
I don't know if you have found an answer yet, but have you tried super.onBackPressed from within your overriding method?
If I were you, I would try:
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
来源:https://stackoverflow.com/questions/6565484/onbackpressed-not-working