getWindow()在Service类中不存在

时间:2019-07-11 06:07:34

标签: android

我在服务类中使用此代码来获取服务中的屏幕截图,但是getWindow()在此处不可用。我该怎么办?

private void takeScreenshot() {
Date now = new Date();
    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

    try {
        // image naming and path  to include sd card  appending name you choose for file
        String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";

        // create bitmap screen capture

        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        File imageFile = new File(mPath);

        FileOutputStream outputStream = new FileOutputStream(imageFile);
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        outputStream.flush();
        outputStream.close();

    } catch (Throwable e) {
        // Several error may come out with file handling or DOM
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

尝试这种方法:

在创建类以及调用相关方法并使用它时,将对活动的引用传递给该活动。但是这种方法可能会导致内存泄漏

void MethodThatUsesActivity(Activity myActivityReference) {
    myActivityReference.getWindow().getDecorView().getRootView();
}