Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

How To Programmatically Take A Screenshot in Android

Uploaded by

Bruno Voltz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

How To Programmatically Take A Screenshot in Android

Uploaded by

Bruno Voltz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

How to programmatically take a screenshot in Android? - Stack Overflow http://stackoverflow.com/questions/2661536/how-to-programmatically-t...

x Dismiss

Join the Stack Overflow Community

Stack Overflow is a community of 7.1 million


programmers, just like you, helping each other.
Join them; it only takes a minute:

Sign up

How to programmatically take a screenshot in Android?

How can I take a screenshot of a selected area of phone-screen not by any program but
from code?

android screenshot

edited Oct 14 '15 at 13:47 asked Apr 18 '10 at 7:58


Hussein El Feky shtpavel
3,196 2 17 43 1,915 3 16 21

3 Not from emulator. I need to make screenshot of part of my programm, and do smth with it in the same
programm. – shtpavel Apr 18 '10 at 8:25

1 Another good reference: stackoverflow.com/a/10296881/439171 – Italo Borssatto Jun 6 '12 at 18:40

17 Answers

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

First, add proper permission to save 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);

1 sur 10 02/05/2017 01:40


How to programmatically take a screenshot in Android? - Stack Overflow http://stackoverflow.com/questions/2661536/how-to-programmatically-t...

} catch (Throwable e) {
// Several error may come out with file handling or OOM
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

edited Oct 28 '16 at 16:29 answered Apr 13 '11 at 14:53


Ramesh Kumar taraloca
490 3 20 5,491 9 29 65

18 this just takes a screenshot of your own program (right?) – Team Pannous Jan 19 '12 at 15:01

21 Hi, Can you describe what is mCurrentUrlMask? I have tried this code but it is always giving me
NullPointerException at Bitmap.createBitmap(v1.getDrawingCache()), Can anybody tell what I am doing
wrong.? Any help is appreciated. Thanks. – Mitesh Sardhara Apr 29 '13 at 19:30

6 Can you please tell me what is, mCurrentUrlMask? – Jayesh Sojitra Oct 25 '13 at 11:12

37 Insted of View v1 = mCurrentUrlMask.getRootView(); I have used View v1 =


getWindow().getDecorView().getRootView(); and it works for me. – enadun Mar 5 '14 at 10:47

5 This answer takes a screenshot of just the app - not the "phone screen" as asked in the question - or am I
doing something wrong. – AlikElzin-kilaka Dec 16 '15 at 3:48

Call this method, passing in the outer most ViewGroup that you want a screen shot of:

public Bitmap screenShot(View view) {


Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}

answered Apr 19 '13 at 17:08


JustinMorris
4,747 19 33

5 This is seems to be cleaner code than the accepted answer. Does it perform as well? – jophde Nov 30 '14 at
5:55

2 I've used it for a while in a few different apps and haven't had any issues. – JustinMorris Dec 4 '14 at 20:43

1 If you want to get a screenshot of the phone, where your app is in the background, what do you pass as the
view ?` – AlikElzin-kilaka Dec 15 '15 at 12:06

Passing getWindow().getDecorView().getRootView() as the view results in taking a screenshot of just


the app - not the screen. – AlikElzin-kilaka Dec 16 '15 at 3:45

This answer takes a screenshot of just the app - not the "phone screen" as asked in the question - or am I
doing something wrong. – AlikElzin-kilaka Dec 16 '15 at 3:49

Note: works only for rooted phone

2 sur 10 02/05/2017 01:40


How to programmatically take a screenshot in Android? - Stack Overflow http://stackoverflow.com/questions/2661536/how-to-programmatically-t...

Programmatically, you can run adb shell /system/bin/screencap -p /sdcard/img.png as


below

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 use as your wish.

edited Oct 13 '14 at 1:39 answered Mar 4 '13 at 18:36


Andrew T. Viswanath Lekshmanan
3,790 5 23 40 5,848 1 22 42

Is it need root access? – zoom Nov 14 '14 at 9:17

3 Yes you need root access. Please check the Note at the heading – Viswanath Lekshmanan Nov 14 '14 at
9:19

Hi, I got a System.err : java.io.IOException: Error running exec(). Command: [su] Working
Directory: null Environment: null , my device is android 5.0 – Eddy Jun 23 '15 at 9:14

@Eddy It depends on your device – Demian May 31 '16 at 20:32

EDIT: have mercy with the downvotes. It was true in 2010 when I answered the
question.

All the programs which allow screenshots work only on rooted phones.

edited Aug 12 '14 at 10:38 answered Apr 18 '10 at 8:41


GDR
1,419 12 22

It looks that these days it's possible on Androids with Tegra based chipset – GDR Dec 27 '11 at 23:05

1 How is it possible.. please elaborate.. – Yogesh Maheshwari Aug 21 '12 at 6:30

1 My tablet running 4.0.3 allows screen shots, not rooted, Acer Iconia A500... – FabianCook Sep 4 '12 at
21:07

4.0.3 - then it's probably one of these new-school tegra tablets – GDR Sep 5 '12 at 11:32

2 Strictly speaking, along with root ADB's "shell" user account has always had permission to do this as that
was the intended use case. What was not historically available (except on occasional builds as a mistake)
was a way for application user id's to do so. – Chris Stratton Apr 30 '15 at 19:20

Mualig answer is very good, but I had the same problem Ewoks describes, I'm not getting the
background. So sometimes is good enough and sometimes I get black text over black
background (depending on the theme).

This solution is heavily based in Mualig code and the code I've found in Robotium. I'm
discarding the use of drawing cache by calling directly to the draw method. Before that I'll try to
get the background drawable from current activity to draw it first.

// Some constants
final static String SCREENSHOTS_LOCATIONS =
Environment.getExternalStorageDirectory().toString() + "/screenshots/";

// Get device dimmensions


Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);

// Get root view


View view = mCurrentUrlMask.getRootView();

// Create the bitmap to use to draw the screenshot


final Bitmap bitmap = Bitmap.createBitmap(size.x, size.y, Bitmap.Config.ARGB_4444);
final Canvas canvas = new Canvas(bitmap);

// Get current theme to know which background to use


final Activity activity = getCurrentActivity();
final Theme theme = activity.getTheme();
final TypedArray ta = theme
.obtainStyledAttributes(new int[] { android.R.attr.windowBackground });
final int res = ta.getResourceId(0, 0);
final Drawable background = activity.getResources().getDrawable(res);

3 sur 10 02/05/2017 01:40


How to programmatically take a screenshot in Android? - Stack Overflow http://stackoverflow.com/questions/2661536/how-to-programmatically-t...

// Draw background
background.draw(canvas);

// Draw views
view.draw(canvas);

// Save the screenshot to the file system


FileOutputStream fos = null;
try {
final File sddir = new File(SCREENSHOTS_LOCATIONS);
if (!sddir.exists()) {
sddir.mkdirs();
}
fos = new FileOutputStream(SCREENSHOTS_LOCATIONS
+ System.currentTimeMillis() + ".jpg");
if (fos != null) {
if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)) {
Log.d(LOGTAG, "Compress/Write failed");
}
fos.flush();
fos.close();
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

answered Jun 25 '12 at 11:37


xamar
219 2 5

I have a listview with android:cacheColorHint="#00000000" in my activity , and I use this code to screenshot ,
I still got a black background , because I found that background that get from theme is black , how can I deal
with this listview? – Wangchao0721 Sep 22 '12 at 14:47

Activity activity = getCurrentActivity giving Eroor undefined method. – Shabbir Dhangot Aug 26 '14 at 7:14

No root permission or no big coding is required for this method.

On adb shell using below command you can take screen shot.

input keyevent 120

This command does not required any root permission so same you can perform from java
code of android application also.

Process process;
process = Runtime.getRuntime().exec("input keyevent 120");

More about keyevent code in android see http://developer.android.com/reference/android


/view/KeyEvent.html

Here we have used. KEYCODE_SYSRQ its value is 120 and used for System Request / Print
Screen key.

As CJBS said, The output picture will be saved in /sdcard/Pictures/Screenshots

edited Nov 4 '16 at 13:00 answered Jan 13 '15 at 9:42


Jeegar Patel
12k 27 93 157

The output picture will be saved here: /sdcard/Pictures/Screenshots – CJBS Apr 29 '15 at 23:00

4 doesn't seem to work on Android 5 – mattlaabs Oct 23 '15 at 16:16

does it require root permission?? – Taranmeet Dec 23 '15 at 5:59

1 will it works on marshmallow ? or will it works in service background @JeegarPatel – Karandeep Atwal Dec
6 '16 at 19:31

1 not worked programmatically, but works from shell. Tried with nougat. – mehmet6parmak Jan 29 at 20:43

4 sur 10 02/05/2017 01:40


How to programmatically take a screenshot in Android? - Stack Overflow http://stackoverflow.com/questions/2661536/how-to-programmatically-t...

As a reference, one way to capture the screen (and not just your app activity) is to capture the
framebuffer (device /dev/graphics/fb0). To do this you must either have root privileges or your
app must be an app with signature permissions ("A permission that the system grants only if
the requesting application is signed with the same certificate as the application that declared
the permission") - which is very unlikely unless you compiled your own ROM.

Each framebuffer capture, from a couple of devices I have tested, contained exactly one
screenshot. People have reported it to contain more, I guess it depends on the frame/display
size.

I tried to read the framebuffer continuously but it seems to return for a fixed amount of bytes
read. In my case that is (3 410 432) bytes, which is enough to store a display frame of 854*480
RGBA (3 279 360 bytes). Yes, the frame, in binary, outputted from fb0 is RGBA in my device.
This will most likely depend from device to device. This will be important for you to decode it =)

In my device /dev/graphics/fb0 permissions are so that only root and users from group
graphics can read the fb0.

graphics is a restricted group so you will probably only access fb0 with a rooted phone using
su command.

Android apps have the user id (uid) = app_## and group id (guid) = app_## .

adb shell has uid = shell and guid = shell, which has much more permissions than an app.
You can actually check those permissions at /system/permissions/platform.xml

This means you will be able to read fb0 in the adb shell without root but you will not read it
within the app without root.

Also, giving READ_FRAME_BUFFER and/or ACCESS_SURFACE_FLINGER permissions on


AndroidManifest.xml will do nothing for a regular app because these will only work for
'signature' apps.

Also check this closed thread for more details.

answered Dec 12 '12 at 10:40


Rui Marques
4,817 1 31 63

1 This works (worked?) on some phones, but note that GPU based phones don't necessarily provide a linear
framebuffer to the applications processor. – Chris Stratton Mar 27 '14 at 14:51

You can try the following library: http://code.google.com/p/android-screenshot-library/ Android


Screenshot Library (ASL) enables to programmatically capture screenshots from Android
devices without requirement of having root access privileges. Instead, ASL utilizes a native
service running in the background, started via the Android Debug Bridge (ADB) once per
device boot.

answered Sep 7 '10 at 13:53


Kuba
751 6 7

1 I tried this.but it takes screenshot of the running app alone. Its cant help if i want to take screenshot of the
homescreen. do you how to take screenshot of the homescreen withthat code? – Jana Oct 15 '10 at 7:14

1 @Janardhanan.S: This is what the question is asking for. Can you elaborate with a new answer instead of
asking a separate question. – trgraglia Feb 8 '11 at 8:28

3 Same Problem with me.. "Native Service Not Running!!" – Yogesh Maheshwari Aug 17 '12 at 10:57

1 Same with me "Native Service Not Running!!".... can anybody add the help text here? – Pankaj Kumar Jun
20 '13 at 9:59

1 same here! "Native Service Not Running!!" and in their latest version 1.2 they use API LEVEL 19 classes,
like Socket for example. – user347187 Apr 15 '14 at 7:42

private void captureScreen() {


View v = getWindow().getDecorView().getRootView();
v.setDrawingCacheEnabled(true);
Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
try {
FileOutputStream fos = new FileOutputStream(new File(Environment
.getExternalStorageDirectory().toString(), "SCREEN"

5 sur 10 02/05/2017 01:40


How to programmatically take a screenshot in Android? - Stack Overflow http://stackoverflow.com/questions/2661536/how-to-programmatically-t...

+ System.currentTimeMillis() + ".png"));
bmp.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

edited Sep 5 '15 at 11:08 answered Aug 27 '14 at 10:31


Jared Rummler Crazy Coder
21.5k 11 72 96 345 1 3 10

Worked fine for me. – Naresh Sharma Dec 17 '14 at 12:20

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


– AndroidGuy May 11 '15 at 6:19

2 This answer takes a screenshot of just the app - not the "phone screen" as asked in the question - or am I
doing something wrong? – AlikElzin-kilaka Dec 16 '15 at 3:56

What about If I need screenshot of an item of listview? – Anshul Tyagi Feb 12 '16 at 10:20

i want to capture in from adapter any idea how can i do it? – Deep Dave Jun 18 '16 at 11:36

My solution is:

public static Bitmap loadBitmapFromView(Context context, View v) {


DisplayMetrics dm = context.getResources().getDisplayMetrics();
v.measure(MeasureSpec.makeMeasureSpec(dm.widthPixels, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(dm.heightPixels, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap returnedBitmap = Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
v.draw(c);

return returnedBitmap;
}

and

public void takeScreen() {


Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_"
+ System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
fout.close();
}
}

Images are saved in the external storage folder.

edited Oct 14 '15 at 13:11 answered Sep 25 '13 at 15:07


Collin James validcat
4,034 1 15 31 3,490 2 21 32

1 You should close the FileOutputStream in a finally block. If you encounter an exception now the stream will
not be closed. – Wotuu May 1 '14 at 9:31

What's the view you're passing to ImageUtils.loadBitmapFromView(this, view) ? – AlikElzin-kilaka Dec


16 '15 at 3:57

1 why do you use v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); ? Doesn't that change the
view (v) ? – serj Jan 28 '16 at 16:23

You can try to do something like this,

Getting a bitmap cache from a layout or a view by doing something like First you gotta

6 sur 10 02/05/2017 01:40


How to programmatically take a screenshot in Android? - Stack Overflow http://stackoverflow.com/questions/2661536/how-to-programmatically-t...

setDrawingCacheEnabled to a layout(a linearlayout or relativelayout, or a view)

then

Bitmap bm = layout.getDrawingCache()

Then you do whatever you want with the bitmap. Either turning it into an image file, or send the
bitmap's uri to somewhere else.

edited Aug 6 '14 at 6:01 answered Mar 5 '11 at 20:07


Pratik Butani Kevin Tan
21.1k 16 105 183 823 5 13

1 This is the best method if it is your app that you are writing to a bitmap. Also, beware of methods which have
delays before taking the cache... like Notify...() for list views. – trgraglia Mar 6 '11 at 19:13

Not just that. The layout must be displayed on the screen first. It's the "cache" you're getting afterall. Tried
hiding the view and taking screenshots in the background(in theory), but it didn't work. – Kevin Tan Mar 14
'11 at 8:51

By far more efficient than other solutions – sivi Aug 18 '15 at 12:03

public class ScreenShotActivity extends Activity{

private RelativeLayout relativeLayout;


private Bitmap myBitmap;

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

relativeLayout = (RelativeLayout)findViewById(R.id.relative1);
relativeLayout.post(new Runnable() {
public void run() {

//take screenshot
myBitmap = captureScreen(relativeLayout);

Toast.makeText(getApplicationContext(), "Screenshot captured..!",


Toast.LENGTH_LONG).show();

try {
if(myBitmap!=null){
//save image to SD card
saveImage(myBitmap);
}
Toast.makeText(getApplicationContext(), "Screenshot saved..!",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
});

public static Bitmap captureScreen(View v) {

Bitmap screenshot = null;


try {

if(v!=null) {

screenshot = Bitmap.createBitmap(v.getMeasuredWidth(),v.getMeasuredHeight(),
Config.ARGB_8888);
Canvas canvas = new Canvas(screenshot);
v.draw(canvas);
}

}catch (Exception e){


Log.d("ScreenShotActivity", "Failed to capture screenshot because:" +
e.getMessage());
}

return screenshot;
}

public static void saveImage(Bitmap bitmap) throws IOException{

ByteArrayOutputStream bytes = new ByteArrayOutputStream();


bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator +
"test.png");

7 sur 10 02/05/2017 01:40


How to programmatically take a screenshot in Android? - Stack Overflow http://stackoverflow.com/questions/2661536/how-to-programmatically-t...

f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}

ADD PERMISSION

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

answered Aug 21 '14 at 12:01


Vaishali Sutariya
2,702 13 18

This answer takes a screenshot of just the app - not the "phone screen" as asked in the question - or am I
doing something wrong? – AlikElzin-kilaka Dec 16 '15 at 3:59

For those who want to capture a GLSurfaceView, the getDrawingCache or drawing to canvas
method won't work.

You have to read the content of the OpenGL framebuffer after the frame has been rendered.
There is a good answer here

answered Apr 10 '15 at 15:57


rockeye
2,223 21 40

I have created a simple library that takes a screenshot from a View and either gives you a
Bitmap object or saves it directly to any path you want

https://github.com/abdallahalaraby/Blink

edited Aug 25 '16 at 22:01 answered Oct 27 '14 at 8:45


Abdallah Alaraby
1,558 1 8 25

Does it requires rooted phone ? – Nilesh Agrawal Feb 10 '15 at 19:20

1 No rooting required :) – Abdallah Alaraby Feb 10 '15 at 20:33

In usage u mentioned Screenshot.takeScreenshot(view, mPath);


imageView.setImageBitmap(Screenshot.getBitmapScreenshot(view, mPath)); How to get view of
current activity. I dont want to use the id of the xml. – Nilesh Agrawal Feb 10 '15 at 20:38

Based on the answer of @JustinMorris above and @NiravDangi here http://stackoverflow.com


/a/8504958/2232148 we must take the background and foreground of a view and assemble
them like this:

public static Bitmap takeScreenshot(View view, Bitmap.Config quality) {


Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), quality);
Canvas canvas = new Canvas(bitmap);

Drawable backgroundDrawable = view.getBackground();


if (backgroundDrawable != null) {
backgroundDrawable.draw(canvas);
} else {
canvas.drawColor(Color.WHITE);
}
view.draw(canvas);

return bitmap;
}

The quality parameter takes a constant of Bitmap.Config, typically either


Bitmap.Config.RGB_565 or Bitmap.Config.ARGB_8888 .

edited Apr 12 '16 at 7:56 answered May 20 '15 at 21:09


Nirav Dangi Oliver Hausler
2,624 2 30 54 1,790 1 13 43

8 sur 10 02/05/2017 01:40


How to programmatically take a screenshot in Android? - Stack Overflow http://stackoverflow.com/questions/2661536/how-to-programmatically-t...

drawing canvas with white color in case background is null did the trick for me. Thanks Oliver – Shaleen Jun
25 '15 at 10:57

If you want to take screenshot from fragment than follow this:

1. Override onCreateView() :
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_one, container, false);
mView = view;
}

2. Logic for taking screenshot:


button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View view = mView.findViewById(R.id.scrollView1);
shareScreenShotM(view, (NestedScrollView) view);
}

3. method shareScreenShotM)() :
public void shareScreenShotM(View view, NestedScrollView scrollView){

bm = takeScreenShot(view,scrollView); //method to take screenshot


File file = savePic(bm); // method to save screenshot in phone.
}

4. method takeScreenShot():
public Bitmap takeScreenShot(View u, NestedScrollView z){

u.setDrawingCacheEnabled(true);
int totalHeight = z.getChildAt(0).getHeight();
int totalWidth = z.getChildAt(0).getWidth();

Log.d("yoheight",""+ totalHeight);
Log.d("yowidth",""+ totalWidth);
u.layout(0, 0, totalWidth, totalHeight);
u.buildDrawingCache();
Bitmap b = Bitmap.createBitmap(u.getDrawingCache());
u.setDrawingCacheEnabled(false);
u.destroyDrawingCache();
return b;
}

5. method savePic():
public static File savePic(Bitmap bm){

ByteArrayOutputStream bytes = new ByteArrayOutputStream();


bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File sdCardDirectory = new File(Environment.getExternalStorageDirectory() +
"/Foldername");

if (!sdCardDirectory.exists()) {
sdCardDirectory.mkdirs();
}
// File file = new File(dir, fileName);
try {
file = new File(sdCardDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
file.createNewFile();
new FileOutputStream(file).write(bytes.toByteArray());
Log.d("Fabsolute", "File Saved::--->" + file.getAbsolutePath());
Log.d("Sabsolute", "File Saved::--->" + sdCardDirectory.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
return file;
}

For activity you can simply use View v1 = getWindow().getDecorView().getRootView();


instead of mView

answered Apr 30 '16 at 6:25


Parsania Hardik
2,028 1 11 30

if you want to capture a view or layout like RelativeLayout or LinearLayout etc. just use

9 sur 10 02/05/2017 01:40


How to programmatically take a screenshot in Android? - Stack Overflow http://stackoverflow.com/questions/2661536/how-to-programmatically-t...

the code :

LinearLayout llMain = (LinearLayout) findViewById(R.id.linearlayoutMain);


Bitmap bm = loadBitmapFromView(llMain);

now you can save this bitmap on device storage by :

FileOutputStream outStream = null;


File f=new File(Environment.getExternalStorageDirectory()+"/Screen Shots/");
f.mkdir();
String extStorageDirectory = f.toString();
File file = new File(extStorageDirectory, "my new screen shot");
pathOfImage = file.getAbsolutePath();
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
Toast.makeText(getApplicationContext(), "Saved at "+f.getAbsolutePath(),
Toast.LENGTH_LONG).show();
addImageGallery(file);
//mail.setEnabled(true);
flag=true;
} catch (FileNotFoundException e) {e.printStackTrace();}
try {
outStream.flush();
outStream.close();
} catch (IOException e) {e.printStackTrace();}

edited Sep 5 '15 at 11:10 answered Feb 27 '15 at 8:50


Jared Rummler Akshay
21.5k 11 72 96 1,597 1 14 22

and where is loadBitmapFromView code? – b devloper Jan 23 at 11:18

protected by Community ♦ Mar 31 '15 at 16:22


Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation
on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

10 sur 10 02/05/2017 01:40

You might also like