What Android code mimics the screenshot function (

2019-07-19 05:14发布

问题:

I am looking for a way to take screenshots of android device programmatically. I have looked at several solutions in stackoverflow that involve taking a screenshot of the running activity. I want to mimic the behavior that is by default triggered in Android by pressing volume down and power button simultaneously. Please note, I don't want to take screenshot of my own activity or running activity. I want to, for example, launch a dialog activity with a button, and when the button is clicked, I finish my activity and start a background task that will take a screenshot of the visible section including status-bar, like holding volume-down and power does. How do I achieve this?

回答1:

If you are taking a screenshot of another Activity you will somehow have to get a reference to the View that encompasses the section of the screen you want to screenshot OR just capture the entire screen. If it is the entire screen you can get that with

// get the top level view from the activity in this context
View theView = getWindow().getDecorView();

Then to capture that View as a Bitmap you can use

// Take the Screen shot of a View
public static Bitmap takeScreenshot(final View theView) {
    theView.setDrawingCacheEnabled(true);
    return theView.getDrawingCache();
}    

// Release the drawing cache after you have captured the Bitmap
// from takeScreenshot()
public static void clearScreenshotCache(final View theView) {
    theView.setDrawingCacheEnabled(false);
}

From there you can save the Bitmap into a JPEG or PNG by calling .compress on the Bitmap.

As for running a task on a background thread there's enough documentation on several ways to do that like here.

Hope that gets you started!