Take a screenshot - Background Service

元气小坏坏 提交于 2019-12-06 02:46:33

问题


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.


回答1:


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?




回答2:


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.




回答3:


Use MediaProjectionManager#createScreenCaptureIntent given in the MediaProjection API of Android. What you are doing now is taking the chatHead's root view's information rather than information present on the complete screen of your device including the status bar at the top.



来源:https://stackoverflow.com/questions/44288546/take-a-screenshot-background-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!