Android Take Screenshot via Code

How to programmatically take a screenshot on Android?

Here is the code that allowed my screenshot to be stored on an SD card and used later for whatever your needs are:

First, you need to add a proper permission to save the file:

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

And this is the code (running in an Activity):

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() + "/" + 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();

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

And this is how you can open the recently generated image:

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);
}

If you want to use this on fragment view then use:

View v1 = getActivity().getWindow().getDecorView().getRootView();

instead of

View v1 = getWindow().getDecorView().getRootView();

on takeScreenshot() function

Note:

This solution doesn't work if your dialog contains a surface view. For details please check the answer to the following question:

Android Take Screenshot of Surface View Shows Black Screen

How to take a screenshot of a current Activity and then share it?

This is how I captured the screen and shared it.

First, get root view from current activity:

View rootView = getWindow().getDecorView().findViewById(android.R.id.content);

Second, capture the root view:

 public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}

Third, store the Bitmap into the SDCard:

public static void store(Bitmap bm, String fileName){
final static String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if(!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}

At last, share the screenshot of current Activity:

private void shareImage(File file){
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");

intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No App Available", Toast.LENGTH_SHORT).show();
}
}

I hope you will be inspired by my codes.

UPDATE:

Add below permissions into your AndroidManifest.xml:

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

Because it creates and accesses files in external storage.

UPDATE:

Starting from Android 7.0 Nougat sharing file links are forbiden. To deal with this you have to implement FileProvider and share "content://" uri not "file://" uri.

Here is a good description how to do it.

How To Programmatically take a screenshot in android of Alert Dialog

Developed on Android 5 emulator and its working. Took Your dialog code and screenshot code from the link you have provided.

This is your AlertDialog

public void showCalc(String title, String message) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("Capture + Open",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Remove Values From Inventory
captureScreenAndOpen();
}
});

builder.setNegativeButton("Capture",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AlertDialog dialog2 =AlertDialog.class.cast(dialog);
takeScreenshot(dialog2);
Context context = getApplicationContext();
Toast.makeText(context, "Screenshot Captured", Toast.LENGTH_LONG).show();
}
});

builder.setNeutralButton("Return", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}

This is screenshot code

private void takeScreenshot(AlertDialog dialog) {
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 = "/data/data/com.rohit.test/test.jpg"; // use your desired path

// create bitmap screen capture
View v1 = dialog.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();
}
}

Screenshot taken

Sample Image

Note1: You can generalize the method takeScreenshot if you change the argument type to View and move dialog.getWindow().getDecorView().getRootView(); to dialog code from where this method is called.

Note2: Saw you updated question. I don't think you can get whole data in screenshot when some of them are hidden. Think it as like a normal screenshot (on computer or even phone). You take picture of only what you can see.

Taking screenshot programmatically in android

bitmap.compress(Bitmap.CompressFormat.JPEG, 0, fos);

First, you are saving this as a JPEG. JPEG is designed for photos, and your screenshot is not a photo.

Second, you are saving this with a quality factor of 0. JPEG uses a lossy compression algorithm, and a quality factor of 0 says "please feel free to make this image be really poor, but compress it as far as you can".

I suggest switching to:

bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

PNG is a better image format for a screenshot with the contents shown in your question. I don't think PNG uses the quality factor value; I put in 100 just to indicate that you want the best possible quality.

Android - How to take screenshot programmatically

If your phone is rooted try this

Process sh = Runtime.getRuntime().exec("su", null,null);

OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();

os.close();
sh.waitFor();

then read img.png as bitmap and convert it jpg as follows

Bitmap screen = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+         
File.separator +"img.png");

//my code for saving
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
screen.compress(Bitmap.CompressFormat.JPEG, 15, bytes);

//you can create a new file name "test.jpg" in sdcard folder.

File f = new File(Environment.getExternalStorageDirectory()+ File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput

fo.close();

you have no access to the screen if your application is in background unless you are rooted, the code above can take the screenshot most effectively of any screen even if you are in background.

UPDATE

Google has a library with which you can take screenshot without rooting, I tried that, But iam sure that it will eat out the memory as soon as possible.

Try http://code.google.com/p/android-screenshot-library/

How to take a screenshot and share it programmatically

Try this for taking screenshot of current Activity:

Android 2.2 :

private static Bitmap takeScreenShot(Activity activity)
{
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;

DisplayMetrics displaymetrics = new DisplayMetrics();
mContext.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

int width = displaymetrics.widthPixels;
int height = displaymetrics.heightPixels;

Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
return b;
}
private static void savePic(Bitmap b, String strFileName)
{
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(strFileName);
if (null != fos)
{
b.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}

How to take snapshot of screen not only app in Android with code

To take screen shot of the device screen, Only if you have root
call the screencap binary like:

Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + Environment.getExternalStorageDirectory()+ "/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor()

And to load that file into a bitmap,Use

public static Bitmap decodeSampledBitmapFromFile(String path,
int reqWidth, int reqHeight) {

// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}

public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {

final int halfHeight = height / 2;
final int halfWidth = width / 2;

// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}

return inSampleSize;
}


Related Topics



Leave a reply



Submit