Android中叠加窗口中的BACK按钮回调

时间:2017-05-21 20:18:13

标签: android overlay keyevent

我在我的应用中显示了来自服务的overlay window。我想在press back button时隐藏窗口。所以要获得back button event,我会执行以下代码

class MyView extends MyLayout{
    public MyView(Context context){
        super(context);
        LayoutInflater.from(context).inflater(R.layout.my_view,this);
    }
}

Class MyLayout extends FrameLayout{
    public MyLayout(Context context){
       super(context);
    }

   @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        Log.e("key event", "" + event.getKeyCode());
        return super.dispatchKeyEvent(event);
    }
}
//service code
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
                        | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS |
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION | WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                PixelFormat.TRANSLUCENT);

final MyView myview = new MyView(this);
windowManager.addView(myview,param);

dispatchKeyEvent方法从未调用过back button pressed。我用Google搜索并发现这是捕获后退按钮事件的方法。不知怎的,它在我的情况下不起作用。我错过了什么?

2 个答案:

答案 0 :(得分:0)

如果您只想捕获back button pressed事件使用:

@override
public void onBackPressed(){
// Do what you need done here 
// ... or pass super.onBackPressed();
}

答案 1 :(得分:0)

真正的问题是window params。我只需要WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH flags来阻止其他应用get key events。所以正确的代码是

//服务代码

final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS |
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION | WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                PixelFormat.TRANSLUCENT);