问题
Hey I have a code that looks like this:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_HOME:
System.out.println("sdfadsfadsf");
finish();
return true; }
} return super.onKeyDown(keyCode, event);}
My problem is, that neither the app terminates nor the println gets executed. Can someone tell me what I do wrong in here? The app should get closed, when a user presses the home key. I do this because of performance issues my users experience when they open up other apps. I could just make the app more performance-efficient but in this type of app, there is really no need to keep it running.
回答1:
By design the Home key cannot be intercepted, thus KEYCODE_HOME will not be sent in any callback. You can only infer when Home key is pressed.
回答2:
You can probably try using onClose in your main. This would allow you to save files or do whatever when you close the app.
Something like...
@Override
protected void onStop() {
super.onStop();
//Do whatever
}
回答3:
I found it here in SO:
Question: Detect home button press in android
Original post: http://nisha113a5.blogspot.com.ar/
Finally, the code in your activity should be:
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean defaultAction = super.onKeyDown(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_HOME) {
Log.i(TAG, "it's into the IF statement!");
}
return defaultAction;
}
回答4:
This key is handled by the framework and is never delivered to applications.
but you can achieve it using Reflection. See this post
来源:https://stackoverflow.com/questions/16288850/keycode-home-doesnt-get-called-android