首页 > 解决方案 > 获取前台服务Android的根视图

问题描述

我有一个带有前台服务的应用程序,可以从麦克风录制然后处理它,现在我想创建另一个在后台运行的前台服务来捕获 android 屏幕然后还处理捕获的图像,但我不知道该怎么做它。这是我发现的用于执行屏幕捕获工作的应用程序,但是一旦我按下应用程序图标并且我无法启动录制服务,它就会关闭,我在这里找到了同样的问题,这是的应用程序的应用程序。如果我使用此代码:

private fun takeScreenshot() {

    val now = Date()
    DateFormat.format("yyyy-MM-dd_hh:mm:ss", now)
    val now2= now.toString().split(" ")
    try {
        // image naming and path  to include sd card  appending name you choose for file
        val mPath: String =
            getExternalFilesDir(null).toString().toString() + "/" + now2 + ".png"
        Log.d("path",mPath)
        // create bitmap screen capture
        val v1 = window.decorView.rootView
        v1.isDrawingCacheEnabled = true
        val bitmap = Bitmap.createBitmap(v1.drawingCache)
        v1.isDrawingCacheEnabled = false
        val imageFile = File(mPath)

        val outputStream = FileOutputStream(imageFile)
        val quality = 100
        bitmap.compress(Bitmap.CompressFormat.PNG, quality, outputStream)
        outputStream.flush()
        outputStream.close()
    } catch (e: Throwable) {
        // Several error may come out with file handling or DOM
        e.printStackTrace()
    }
}

我无法从前台服务获取 rootview。请帮我

标签: androidkotlinscreen-capture

解决方案


推荐阅读