Monday, September 28, 2015

android - How to take ScreenShot programmatically

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#c4d0eb"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Take ScreenShot"
        />
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn"
        android:src="@drawable/animal"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.ActionBar;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.provider.MediaStore;


public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        final Button btn = (Button) findViewById(R.id.btn);

        ActionBar ab = getActionBar();
        ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FF54A9EB")));

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Take the screenshot
                Bitmap screenShot = TakeScreenShot(rl);

                /*
                    MediaStore
                        The Media provider contains meta data for all available media
                        on both internal and external storage devices.

                    MediaStore.Images
                        Contains meta data for all available images.

                    insertImage(ContentResolver cr, Bitmap source, String title, String description)
                        Insert an image and create a thumbnail for it.
                */

                // Save the screenshot on device gallery
                MediaStore.Images.Media.insertImage(
                        getContentResolver(),
                        screenShot,
                        "Image",
                        "Captured ScreenShot"
                );

                // Notify the user that screenshot taken.
                Toast.makeText(getApplicationContext(), "Screen Captured.",Toast.LENGTH_SHORT).show();
            }
        });
    }

    // Custom method to take screenshot
    public Bitmap TakeScreenShot(View rootView)
    {
        /*
            public static Bitmap createBitmap (int width, int height, Bitmap.Config config)
                Returns a mutable bitmap with the specified width and height.
                Its initial density is as per getDensity().

                Parameters
                    width : The width of the bitmap
                    height : The height of the bitmap
                    config : The bitmap config to create.

                Throws
                    IllegalArgumentException : if the width or height are <= 0
        */

        /*
            Bitmap.Config
                Possible bitmap configurations. A bitmap configuration describes how pixels
                are stored. This affects the quality (color depth) as well as the ability
                to display transparent/translucent colors.

                ARGB_8888
                    Each pixel is stored on 4 bytes.
        */

        // Screenshot taken for the specified root view and its child elements.
        Bitmap bitmap = Bitmap.createBitmap(rootView.getWidth(),rootView.getHeight(),Config.ARGB_8888);

        /*
            Canvas
                The Canvas class holds the "draw" calls. To draw something, you need
                4 basic components:
                    A Bitmap to hold the pixels,
                    a Canvas to host the draw calls (writing into the bitmap),
                    a drawing primitive (e.g. Rect, Path, text, Bitmap),
                    and a paint (to describe the colors and styles for the drawing).
        */

        /*
            public Canvas (Bitmap bitmap)
                Construct a canvas with the specified bitmap to draw into. The bitmap must be mutable.
                The initial target density of the canvas is the same as the given bitmap's density.

                Parameters
                bitmap : Specifies a mutable bitmap for the canvas to draw into.
        */
        Canvas canvas = new Canvas(bitmap);
        rootView.draw(canvas);
        return bitmap;
    }
}
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cfsuman.me.androidcodesnippets" >

    <uses-permission android:name="android.permission.INTERNET" />
    <!--
        public static final String WRITE_EXTERNAL_STORAGE
            Starting in API level 19, this permission is not required to read/write
            files in your application-specific directories returned by
            getExternalFilesDir(String) and getExternalCacheDir().

        Protection level: dangerous

        Constant Value: "android.permission.WRITE_EXTERNAL_STORAGE"
    -->
    <!-- This permission required to save captured screenshot on device gallery -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


More android examples