How to take screenshot programatically in android

In android there are lot of application which allows you to take the screenshot . But what if we want to do the same programatically, the solution is it is possible in android to get the bitmap of the entire screen in android. In this tutorial we will see how to get the screenshot of an application programatically in android.

First step is to give id to the parent layout in your reference file. suppose if  it is relative layout , it will be

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto" 
 xmlns:tools="http://schemas.android.com/tools" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:id="@+id/rl_parent" 
 tools:showIn="@layout/activity_main">

<!--your layout code will come here-->

</RelativeLayout>

Now for taking screenshot give the following code in your class file.

RelativeLayout layout = (RelativeLayout)findViewById(R.id.rl_parent);

Bitmap bitmap = Bitmap.createBitmap(layout.getWidth(), layout.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Drawable bgDrawable = layout.getBackground();

The above bitmap will contain the screenshot of your screen.

Suppose if you want to save in your external storage after taking screenshot,use the below method on your action which is proving complete code for taking screenshot and saving in external storage.

private void captureScreen() {

RelativeLayout layout = (RelativeLayout)findViewById(R.id.rl_parent);

Bitmap bitmap = Bitmap.createBitmap(layout.getWidth(), layout.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Drawable bgDrawable = layout.getBackground();
if (bgDrawable!=null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
layout.draw(canvas);

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "temporary_file.jpg");
try {
f.createNewFile();
new FileOutputStream(f).write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}

}

You need to have permission for external storage for doing the above mentioned task.And
suppose if you want to take screen shot of only certain section of the screen, then
instead of mentioning parent layout id mention that layouts id only.

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *