Take a screenshot - Background Service

20,057

Solution 1

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.

Solution 2

To get a screenshot containing views not belonging to your app you'll need to use the MediaProjectionManager.

See How to take a screen shot with status bar contents in android application?

Share:
20,057
Mister JJ
Author by

Mister JJ

Updated on July 04, 2020

Comments

  • Mister JJ
    Mister JJ almost 4 years

    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 Picture

    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.