How to take screenshot of your phone in android through code?

By | April 7, 2012

Hey all…

This is a very simple thing to do in android.
Just copy this code to see this.

here is the main java file

package pack.coderzheaven;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class ScreenShotDemo extends Activity {
	LinearLayout L1;
	ImageView image;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        L1 = (LinearLayout) findViewById(R.id.LinearLayout01);
        Button but = (Button) findViewById(R.id.Button01);
        but.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
		        View v1 = L1.getRootView();
		        v1.setDrawingCacheEnabled(true);
		        Bitmap bm = v1.getDrawingCache();
		        BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
		        image = (ImageView) findViewById(R.id.ImageView01);
		        image.setBackgroundDrawable(bitmapDrawable);
		    }
	   });
  }
}

And this is the layout file main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/LinearLayout01"
    >
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Take Screenshot"
    android:id="@+id/Button01"
    />

  <ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Take Screenshot"
    android:id="@+id/ImageView01"
    />
</LinearLayout>
Screenshot in android

ScreenShot in android

Leave a Reply

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