Android take screenshot programmatically

Generally we are taking screenshots in android devices by pressing power + volume down button. Now arises a question that is it possible to take screenshot programmatically from android app? Yes, it is possible to capture screenshot within our android app programmatically. In this tutorial, you will learn how to take screenshot programmatically of an activity or a view.

Let’s Get it Working

In this tutorial we are going to learn how to take screenshot programmatically in android and store it in storage as well. To really understand the process we will create an app. The App contains simple view having buttons to capture screenshot and save it in storage, image view to show screenshot. I assume that you have already created a new android project. Source Code is available on GitHub.

Step 1) Update strings.xml.

Add the below string values to the string.xml located in res ⇒ values ⇒ strings.xml.

Step 3) Create ScreenshotUtil class.

Create a new package named helper and create ScreenshotUtil class and add below code in it. The code will create singleton class that is used to take screen shot. This ScreenshotUtil class contains following methods:-

Bitmap takeScreenshotForView(View view) :- Measures and takes a screenshot of the provided viewBitmap takeScreenshotForScreen(Activity activity) :- Measures and takes a screenshot of the provided activity

Step 4) Create FileUtil class.

Create a new package named helper and create FileUtil class and add below code in it. The code will create singleton class that is used to save screen shot to storage. This FileUtil class contains following method:-

void storeBitmap(Bitmap bitmap, String filePath) :- Stores the given Bitmap to a path on the device.

Step 5) Update build.gradle file.

To manage run time permission I have used Dexter Android library that simplifies the process of requesting permissions at runtime. you need to add the following compile line to your Gradle dependencies block in your build.gradle file and rebuilt the project.

dependencies {
...
implementation 'com.karumi:dexter:5.0.0'
}

Step 6) Update MainActivity class.

Open class named MainActivity and add below code. Here I have written the code to initialize the views, registered the button’s onClick listeners, also written the logic to take screenshot programmatically and save it to storage.