Android Window Manager阻止系统后退键

时间:2017-09-27 21:33:47

标签: android overlay back-button android-windowmanager

我有一个像Facebook聊天buble的浮动视图,但与它不同,我的叠加层有一个EditText,需要可以集中精力。

这是我的浮动视图代码

        //Inflate the floating view layout we created
        mFloatingView = LayoutInflater.from(this).inflate(R.layout.floating_widget_layout, null);

        //Add the view to the window.
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                PixelFormat.TRANSLUCENT);

        //Specify the view position
        params.gravity = Gravity.TOP | Gravity.START;        //Initially view will be added to top-left corner
        params.x = 0;
        params.y = 100;

        //Add the view to the window
        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        mWindowManager.addView(mFloatingView, params);

这几乎是好事,但有一个问题。当我从服务创建叠加层时,系统后退按钮无法正常工作。如果我使用FLAG_NOT_FOCUSABLE系统按钮;家庭,最近和后面的工作如预期。我在SO做了一些研究,发现这是一个安全问题,所以我开始找到替代解决方案,然后发现this然后更改了我的代码

// Wrapper for intercepting System/Hardware key events
ViewGroup wrapper = new FrameLayout(this) {
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode()==KeyEvent.KEYCODE_BACK) {
            Log.v("Back", "Back Key");
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
};

//Inflate the floating view layout we created
mFloatingView = LayoutInflater.from(this).inflate(R.layout.floating_widget_layout, wrapper);

//Add the view to the window.
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.TYPE_PHONE,
        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
        PixelFormat.TRANSLUCENT);

//Specify the view position
params.gravity = Gravity.TOP | Gravity.START;        //Initially view will be added to top-left corner
params.x = 0;
params.y = 100;

//Add the view to the window
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mFloatingView, params);

现在我可以从我的浮动视图中取回按钮但是如何将此事件(反压)传递给前台应用程序(其他应用程序,而不是我的)?我找到了this,但它没有帮助我

如果有人可以帮助我或至少提供线索,我将不胜感激

摘要

我有一个叠加视图,它需要是可聚焦的,但是当它可以聚焦时,按下按钮不工作我怎么能解决这个问题?

1 个答案:

答案 0 :(得分:-1)

这个教程好像有解决办法:https://www.geeksforgeeks.org/how-to-make-a-floating-window-application-in-android/

他们最初设置 FLAG_NOT_FOCUSABLE 以便覆盖不会干扰系统返回功能等。他们在 EditText 上设置 onTouch 侦听器并在那时将标志更新为 FLAG_NOT_TOUCH_MODAL 以便文本可以进入。