如何从服务中绘制叠加层

时间:2017-07-20 09:50:46

标签: java android

我的应用程序应该在特定时间绘制叠加层(蓝光滤镜)。现在我有一个名为

的方法
private void drawOverlay()

在正常情况下哪种情况完全正常。但是,我想从服务中使用此方法,该服务在后台运行并且已在运行,以便我可以在特定时间绘制叠加层。在某些情况下,这有效,但有时我会收到以下错误: -

  

java.lang.RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序

我理解这与UI thread有关,我应该使用Looperhandler我已阅读文档,但我无法完全解决我应该如何做到这一点。

有人可以澄清这一点。

 private void drawOverlay() {
    log("drawing overlay");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        log("overlay >m checking permission");
        wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        if (permissionGranted) {
            log("permission granted");
            LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.screen_dimmer, null);
            WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            | WindowManager.LayoutParams.FLAG_FULLSCREEN
                            | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                            | WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                            | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
                    PixelFormat.TRANSLUCENT);
            wm = (WindowManager) getSystemService(WINDOW_SERVICE);
            wm.addView(view, params);
            overlayDrawn = true;
        } else {
            log("no permission");
        }
    } else {
        log("overlay drawing no permission needed (<m)");
        wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        if (permissionGranted) {
            LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.screen_dimmer, null);
            WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            | WindowManager.LayoutParams.FLAG_FULLSCREEN
                            | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                            | WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                            | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
                    PixelFormat.TRANSLUCENT);
            wm = (WindowManager) getSystemService(WINDOW_SERVICE);
            wm.addView(view, params);
        }
    }
}

在服务启动之前,应用会检查它是否有权绘制叠加层,即permissionGranted布尔值来自的地方,只有在SDK版本高于M时才需要。

0 个答案:

没有答案