Get screenshot of surfaceView in Android

sajar picture sajar · Mar 1, 2013 · Viewed 10.2k times · Source

In my application I have view with some buttons and SurfaceView. I must take screenshot of this view, but in place of SurfaceView is only black field. I try solutions which I found on stackoverflow, but they don't work for me.

This is my code which I usualy take screenshots:

File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/folder");
if (!folder.exists()) {
    folder.mkdir();
}
String path = folder.getAbsolutePath() + "snapshot.png";
File file = new File(path);
file.createNewFile();

View view = this.findViewById(android.R.id.content).getRootView();
view.setDrawingCacheEnabled(true);
Bitmap drawingCache = view.getDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(drawingCache);

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(file);
    bitmap.compress(CompressFormat.PNG, 100, fos);
} finally {
    bitmap.recycle();
    view.setDrawingCacheEnabled(false);
    if (fos != null) {
        try {
            fos.close();
        } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }
}

Maybe someone can help.

Answer