How to take a screenshot programmatically in Android?

Please follow and like us:

Generally we are taking screenshots in android devices by pressing power + volume down button. But what about to do that things in our android. is it possible to take screenshot programmatically from android app? yes. Here I share simple logic to capture screenshot by pressing button, refresh it in gallery list and open captured image.power + volume down button. But what about to do that things in our android. is it possible to take screenshot programmatically from android app? yes. Here I share simple logic to capture screenshot by pressing button, refresh it in gallery list and open captured image.

How to take a screenshot programmatically in Android?

First we need to declare following permission in AndroidMainifest.xml file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Add button(for performing operation) in layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnTakeScreenshot"
        android:text="Take Screenshot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

Logic of capturing screenshot

Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

try {
    // image naming and path  to include sd card  appending name you choose for file
    String mPath = Environment.getExternalStorageDirectory().toString() + "/PICTURES/Screenshots/" + now + ".jpg";

    // create bitmap screen capture
    View v1 = getWindow().getDecorView().getRootView();
    v1.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
    v1.setDrawingCacheEnabled(false);

    File imageFile = new File(mPath);

    FileOutputStream outputStream = new FileOutputStream(imageFile);
    int quality = 100;
    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
    outputStream.flush();
    outputStream.close();

} catch (Throwable e) {
    // Several error may come out with file handling or OOM
    e.printStackTrace();
}

Logic of opening captured screenshot

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);

Logic of refreshing gallery to see our latest screenshot

MediaScannerConnection.scanFile(this,
        new String[]{imageFile.toString()}, null,
        new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
                Log.i("ExternalStorage", "Scanned " + path + ":");
                Log.i("ExternalStorage", "-> uri=" + uri);
            }
        });

Complete Logic

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private Button btnTakeScreenshot;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnTakeScreenshot= (Button) findViewById(R.id.btnTakeScreenshot);

        btnTakeScreenshot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takeScreenshot();
            }
        });

    }

    private void takeScreenshot() {
        Date now = new Date();
        android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

        try {
            // image naming and path  to include sd card  appending name you choose for file
            String mPath = Environment.getExternalStorageDirectory().toString() + "/PICTURES/Screenshots/" + now + ".jpg";

            // create bitmap screen capture
            View v1 = getWindow().getDecorView().getRootView();
            v1.setDrawingCacheEnabled(true);
            Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
            v1.setDrawingCacheEnabled(false);
            File imageFile = new File(mPath);
            FileOutputStream outputStream = new FileOutputStream(imageFile);
            int quality = 100;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            outputStream.flush();
            outputStream.close();


            MediaScannerConnection.scanFile(this,
                    new String[]{imageFile.toString()}, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Log.i("ExternalStorage", "Scanned " + path + ":");
                            Log.i("ExternalStorage", "-> uri=" + uri);
                        }
                    });
            
            openScreenshot(imageFile);
        } catch (Throwable e) {
            // Several error may come out with file handling or OOM
            e.printStackTrace();
        }
    }

    private void openScreenshot(File imageFile) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(imageFile);
        intent.setDataAndType(uri, "image/*");
        startActivity(intent);
    }

}

That’s it. you can now add capturing android screenshot programmatically in your android app.

 

nirav kalola