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 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
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.
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.
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.
How to programmatically take a screenshot of open current activity in Android?
1-Create layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativelayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Create ScreenShot" />
<ImageView
android:id="@+id/sowscreenshot"
android:layout_width="216dp"
android:layout_height="360dp"
android:layout_below="@+id/btn"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />
</RelativeLayout>
2-Create Activity
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
Button btn_screenshoot;
int i = 0;
ImageView imgv_showscreenshot;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgv_showscreenshot = (ImageView) findViewById(R.id.showscreenshot);
btn_screenshoot = (Button) findViewById(R.id.btn);
btn_screenshoot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View view = findViewById(R.id.relativelayout);
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
// set screenshot bitmapdrawable to imageview
imgv_showscreenshot.setBackgroundDrawable(bitmapDrawable);
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
// we check if external storage is available, otherwise
// display an error message to the user using Toast Message
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()
+ "/ScreenShots");
directory.mkdirs();
String filename = "screenshot" + i + ".jpg";
File yourFile = new File(directory, filename);
while (yourFile.exists()) {
i++;
filename = "screenshot" + i + ".jpg";
yourFile = new File(directory, filename);
}
if (!yourFile.exists()) {
if (directory.canWrite()) {
try {
FileOutputStream out = new FileOutputStream(
yourFile, true);
bitmap.compress(Bitmap.CompressFormat.PNG, 90,
out);
out.flush();
out.close();
Toast.makeText(
MainActivity.this,
"File exported to /sdcard/ScreenShots/screenshot"
+ i + ".jpg",
Toast.LENGTH_SHORT).show();
i++;
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
Toast.makeText(MainActivity.this,
"Sorry SD Card not available in your Device!",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
3-Add permission to Manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
How to programmatically take a screenshot in Android without root or adb?
On Android 5.0+, use the media projection APIs. They are somewhat under-documented. This sample project demonstrates how to take screenshots.
On Android 4.4 and lower, this is not possible, outside of perhaps some security flaws on specific device models.
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();
}
}
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 programmatically take screenshot of an android application without notification and navigation bars
take the drawing cache of the root Layout as below:
//onCreate
setContentView(R.layout.activity_main);
layout = (RelativeLayout) findViewById(R.id.activity_main);
layout.setDrawingCacheEnabled(true);
And to get bitmap, the usual way,
Bitmap bitmap = layout.getDrawingCache();
activity_main:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="@color/colorPrimary" />
<!--other content-->
</RelativeLayout>
Related Topics
How to Get Imsi Number in Android Using Command Line
Android Emulator Is Start But Window Show Blank Screen
React Native | Failed to Install the App. Please Accept All Necessary Sdk Licenses Using Sdk Manager
How to Set Up Android Studio to Work Completely Offline
How to Format Credit Card Expiry Date in Mm/Yy When Entered by User
How to Remove Android Auto-Suggest Underlining in Edittext
How to Set Value for Each Item Button Increase and Decrease Click and Set That Value in Text View
Android - Transform Classes With Dex for Debug
How to Painlessly Change My App Title Text Color
How to Make User Login from Only One Device At a Time
How to Set Align (Right or Left) of Text in Textview, Programmatically
How to Know Location Area Code and Cell Id in Android Phone
Clear Cache in Android Application Programmatically
How to Get the Height of Recyclerview Item in "Onbindviewholder"
How to Change Listview Height Dynamically in Android
Changing Background Color of the Layout on a Button Click in Android