android keycode home,Keycode_home doesn't get called ANDROID

问题

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值