Android 结合WindowManager和WindowManager.LayoutParams显示窗口及BACK/HOME按键监听


一 声明对象

    private WindowManager mWindowManager;
    private WindowManager.LayoutParams mWindowLayoutParams;
    private View mScreenshotLayout;


二 创建对象

        // Setup the window that we are going to use
        mWindowLayoutParams = new WindowManager.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 0, 0,
                isRom ? WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL : WindowManager.LayoutParams.TYPE_SCREENSHOT,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
                    | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                    | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED,
                PixelFormat.TRANSLUCENT);
        mWindowLayoutParams.setTitle("ScreenshotAnimation");
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mScreenshotLayout = layoutInflater.inflate(R.layout.global_screenshot, null);


备注:

A  android.view.WindowManager.LayoutParams.LayoutParams(int w, int h, int xpos, int ypos, int _type, int _flags, int _format)

B  WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL 和 WindowManager.LayoutParams.TYPE_SCREENSHOT窗口级别

C 常改变的属性:

        mWindowLayoutParams.flags
        mWindowLayoutParams.privateFlags
        mWindowLayoutParams.screenOrientation
        // mWindowLayoutParams.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
        // mWindowLayoutParams.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;


三 显示窗口

mWindowManager.addView(mScreenshotLayout, mWindowLayoutParams);


四 监听BACK/HOME按键

        mScreenshotLayout.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                switch (event.getKeyCode()) {
                    case KeyEvent.KEYCODE_HOME:
                        // TODO
                        return true;
                    case KeyEvent.KEYCODE_BACK:
                        // TODO
                        return true;
                }
                return false;
            }
        });

        mScreenshotLayout.post(new Runnable() {
            @Override
            public void run() {
                mScreenshotLayout.setFocusable(true);
                mScreenshotLayout.setFocusableInTouchMode(true);
                mScreenshotLayout.requestFocus();
            }
        });


注意:监听BACK/监听HOME按键时必须使得相应的View获取焦点(如上 使用post方式取得焦点),否则setOnKeyListener的onKey方法永远不会被回调,按键就监听不到!



你可能感兴趣的:(Android,基础知识)