Skip to content
Advertisement

Take a screenshot – Background Service

I’m trying to take a screenshot using a background service. This service is like a Facebook chathead, but I want it to take an screenshot when I do a click.

Preview Pickture

I’ve developed some code but it doesn’t work. The last I’ve tried was:

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

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

        // create bitmap screen capture
        Bitmap bitmap;
        View v1 = chatHead.getRootView();
        v1.setDrawingCacheEnabled(true);
        bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        OutputStream fout = null;
        File imageFile = new File(mPath);

        try {
            fout = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
            fout.flush();
            fout.close();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

But is taking an screenshot to my button not to the screen.

I know the problem is here:

View v1 = chatHead.getRootView();

But I don’t know how to fix it. Can anyone help me?

I’m actually using Android Studio 2.2.2 and Android 4.0 or greater.

Advertisement

Answer

For Lollipop and above you can use the MediaProjection API of Google to take the screenshot but you need to ask for the permission from the user.

You can find the sample screen capture code using MediaProjection Here

For the devices less then Lollipop you need root permission for it.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement