Search code examples
javaandroidlibgdx

Libgdx error on Android when taking screen shot


I created a game that has a button that will take a screen shot when clicked.

    ChangeListener changeListener = new ChangeListener() {

                    //take screenshot and share
                    if(actor.equals(shareBtn)){
                        byte[] pixels = ScreenUtils.getFrameBufferPixels(0, 0, Gdx.graphics.getBackBufferWidth(), Gdx.graphics.getBackBufferHeight(), true);
                        Pixmap pixmap = new Pixmap(Gdx.graphics.getBackBufferWidth(), Gdx.graphics.getBackBufferHeight(), Pixmap.Format.RGBA8888);
                        BufferUtils.copy(pixels, 0, pixmap.getPixels(), pixels.length);
                        PixmapIO.writePNG(Gdx.files.external("screenShot.png"), pixmap);
                        pixmap.dispose();
                    }

 };

When I run the game on pc there's no problem but when I run it on android I get this error (my phone has an external sd card).

com.badlogic.gdx.utils.GdxRuntimeException: Error writing file: screenShot.png (External)

Caused by: java.io.FileNotFoundException: /storage/emulated/0/screenShot.png: open failed: EACCES (Permission denied)

Solution

  • Make sure you have added permission to write external storage in your manifest file, if you are targeting Android SDK<23 else take permission at run-time.

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>