What Android code mimics the screenshot function (volume down and power button simultaneously)?

感情迁移 提交于 2019-12-13 16:23:15

问题


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!



来源:https://stackoverflow.com/questions/38811233/what-android-code-mimics-the-screenshot-function-volume-down-and-power-button-s

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