我一直在尝试使用以下代码禁用主页按钮:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_HOME) {
Log.i("TAG", "Press Home");
System.exit(0);
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
@Override
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
super.onAttachedToWindow();}
}
但是这会使应用程序崩溃。
崩溃是由以下行引起的:
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
为什么会这样?该如何解决?
崩溃日志:
06-25 17:47:18.620 18125-18125/com.example.myapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nandagp.qapp, PID: 18125
java.lang.IllegalArgumentException: Window type can not be changed after the window is added.
at android.os.Parcel.readException(Parcel.java:1962)
at android.os.Parcel.readException(Parcel.java:1904)
at android.view.IWindowSession$Stub$Proxy.relayout(IWindowSession.java:966)
at android.view.ViewRootImpl.relayoutWindow(ViewRootImpl.java:7029)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2264)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1738)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7745)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
at android.view.Choreographer.doCallbacks(Choreographer.java:723)
at android.view.Choreographer.doFrame(Choreographer.java:658)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
答案 0 :(得分:0)
您应该删除此代码
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
通过onAttachedToWindow()
方法并将其放入onCreate
方法中。
希望这会有所帮助
PS:对于主页按钮替代,read this post。禁用它并不容易,也不建议这样做,这将导致用户无法退出您的应用程序,并且(imo)除非您正在kiosk mode中运行,否则这不是一个好主意。因此,请仔细考虑是否确实需要这样做,如果确实需要,请参考我发布的第一个链接
答案 1 :(得分:0)
当用户按下“ KEYCODE_HOME”时,您将“关闭”应用程序:
if (keyCode == KeyEvent.KEYCODE_HOME) {
Log.i("TAG", "Press Home");
System.exit(0);
您将删除System.exit(0)