after taking screenshot the layout are streached - android

I created screen shot activity in programatically in android.using scroll view the after taking screen shot the layout are stretched. I will give the images for before taking after taking screen shot.this will help you to understand my problem.i don't know how to tell?
before taking screen shot the layout ,
after taking screen shot the layout
you know the difference of two images.the activity after taking screen shot it extended i don't know why it happen? how to solve this?
My code :
public class MainActivity extends AppCompatActivity {
File cacheDir;
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button print = (Button) findViewById(R.id.btn_print);
print.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeScreenShot();
}
});
}
private void takeScreenShot() {
View u = findViewById(R.id.activity_main);
int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
u.measure(spec, spec);
u.layout(0, 0, u.getMeasuredWidth(), u.getMeasuredHeight());
Bitmap b = getBitmapFromView(u,u.getMeasuredHeight(),u.getMeasuredWidth());
final String root = Environment.getExternalStorageDirectory().toString();
File myPath = new File(root + "/saved_img");
myPath.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+n+".jpg";
File file = new File(myPath, fname);
FileOutputStream fos = null;
if(file.exists()) file.delete();
try{
fos = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch(FileNotFoundException e){
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
Toast.makeText(this,"screen captured",Toast.LENGTH_SHORT).show();
}
public Bitmap getBitmapFromView(View u, int totalHeight, int totalWidth){
Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth,totalHeight , Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = u.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
u.draw(canvas);
return returnedBitmap;
}
}
xml :
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.own.scrollviewimg.MainActivity"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="print"
android:id="#+id/btn_print"
/>
<ScrollView
android:id="#+id/horizontalscroll"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ImageView
android:layout_width="500dp"
android:layout_height="200dp"
android:src="#mipmap/ic_launcher"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/testdata"
android:textSize="25sp"
android:textStyle="bold"
/>
</LinearLayout>
</ScrollView>
</LinearLayout>
</RelativeLayout>

try this code
private void takeScreenShot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
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();
} catch (Throwable e) {
e.printStackTrace();
}
}

In your takeScreenShot() block, why are you using View.MeasureSpec
You can use view.getMeasuredHeight() and view.getMeasuredWidth() to the the height and width from the root view itself and also try to get the view from already inflated root by
View view = getWindow().getDecorView().getRootView();
So just comment out
/* int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
u.measure(spec, spec);
u.layout(0, 0, u.getMeasuredWidth(), u.getMeasuredHeight()); */
and the rest is fine
Note: the width of your ImageView may be more than the current screen size

finally i found the answer.it's simple.i just recall the layout on after button click.
my solved answer :
print.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeScreenShot();
setContentView(R.layout.activity_main);
}
});

Related

Take whole "Screenshot" of a scrollable View

In my Fragment's layout i have a ScrollView with a LinearLayout inside
<ScrollView
android:id="#+id/scrollview"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- Other views -->
</LinearLayout>
</ScrollView>
So i need to create and share a picture of entire content of scrollview. All solutions i've tried take screenshot only of the visible area, and not of entire scrollview content. How can i do?
I hope this is work for you.. source here. this is not technically a screenshot code. but this code convert the whole layout view into bitmap
Bitmap bitmap = getBitmapFromView(scrollview, scrollview.getChildAt(0).getHeight(), scrollview.getChildAt(0).getWidth());
//create bitmap from the ScrollView
private Bitmap getBitmapFromView(View view, int height, int width) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return bitmap;
}
call below method getYourLayout() where you want to take snap of your layout. In this i attach layout in one dialog & take snapshop of root layout whithout showing dialog to user. All thing happens in background.
private void getYourLayout() {
try {
Dialog fb_event_info = new Dialog(YourActivity.this);
fb_event_info.requestWindowFeature(Window.FEATURE_NO_TITLE);
fb_event_info.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
fb_event_info.setContentView(R.layout.yourXmlLayoutFile);
final LinearLayout lnr_fb_info = (LinearLayout) fb_event_info.findViewById(R.id.container);
TextView tv_fb_event_name = (TextView) fb_event_info.findViewById(R.id.tv_fb_event_name);
tv_fb_event_name.setTypeface(Global.setCubanoFont(EventDetailActivity.this));
tv_fb_event_name.setText(tv_event_name.getText().toString());
lnr_fb_info.setDrawingCacheEnabled(true);
lnr_fb_info.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
lnr_fb_info.layout(0, 0, lnr_fb_info.getMeasuredWidth(), lnr_fb_info.getMeasuredHeight());
lnr_fb_info.buildDrawingCache(true);
bitmap = Bitmap.createBitmap(lnr_fb_info.getDrawingCache());
saveImage(bitmap);
} catch (Exception e) {
}
}
This Function is for Saving your Bitmap as file.
private void saveImage(Bitmap bitmap) {
try {
Log.e("----------in---", "saveImage....: ");
if (!rootFile.exists())
rootFile.mkdirs();
long time = System.currentTimeMillis();
fname = "mynight-" + time + ".png";
rootFile = new File(rootFile, fname);
Log.e("----------in---", "saveImage...1.: ");
try {
FileOutputStream Fout = new FileOutputStream(rootFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, Fout);
sendShareFb();
Fout.flush();
Fout.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Below function is for share your image on facebook.
private void sendShareFb() {
try {
Log.e("----------in---", "sendShareFb....: ");
Intent fbIntent = new Intent(Intent.ACTION_SEND);
File imageFile = new File(rootFile.toString());
fbIntent.putExtra(Intent.EXTRA_TEXT, "Share..");
fbIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
fbIntent.setType("image/jpeg/png");
PackageManager pm = getPackageManager();
List<ResolveInfo> lract = pm.queryIntentActivities(fbIntent, PackageManager.MATCH_DEFAULT_ONLY);
boolean resolved = false;
for (ResolveInfo ri : lract) {
if (ri.activityInfo.name.toLowerCase().contains("facebook")) {
fbIntent.setClassName(ri.activityInfo.packageName, ri.activityInfo.name);
resolved = true;
break;
}
}
if (!resolved) {
Toast.makeText(EventDetailActivity.this, "Vous ne semblez pas avoir Facebook installé sur cet appareil", Toast.LENGTH_SHORT).show();
}
startActivity(resolved ? fbIntent : Intent.createChooser(fbIntent, "Choose one"));
} catch (final ActivityNotFoundException e) {
e.printStackTrace();
}
}
Sure that this will Help you. Because this solution has fixed my problem many time.

Listview Items not getting displayed when converting XML Layout to bitmap image

I've been trying to convert an XML Layout to bitmap image. When i click on the convert button, image is being generated. But my ListView items are not getting displayed. How can i do that?
Following is my code
mView = findViewById(R.id.f_view);
mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(this);
mView.setDrawingCacheEnabled(true);
mView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
mView.layout(0, 0, mView.getMeasuredWidth(), mView.getMeasuredHeight());
mView.buildDrawingCache(true);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
Bitmap b = Bitmap.createBitmap(mView.getDrawingCache());
mView.setDrawingCacheEnabled(false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Expense Calculator" + File.separator + "Expense.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
Toast.makeText(null, getApplicationContext()+ "Image Generated", Toast.LENGTH_SHORT).show();
fo.close();
} catch (Exception e) {
}
//finish();
}
}
and my xml code is as follows
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<include android:id="#+id/f_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
layout="#layout/view_expense"
android:layout_above="#id/button1"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="54dp"
android:background="#drawable/cimage" />
</RelativeLayout>
What should i do to get my listview items displayed? Can Someone help me please?
Thanks
Enable drawing cache only when you want to get Bitmap from on-click.
mView.buildDrawingCache(true);
Remove above line form onCreate() methdod.
You Need to disable DrawingCache immediately after generating Bitmap from View
like below code:
mView.destroyDrawingCache();
Try Below onClick Code:
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
mView.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(mView.getDrawingCache());
mView.setDrawingCacheEnabled(false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Expense Calculator" + File.separator + "Expense.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
Toast.makeText(null, getApplicationContext()+ "Image Generated", Toast.LENGTH_SHORT).show();
fo.close();
} catch (Exception e) {
}
//finish();
}
Use Below method to get bitmap from view you can pass view in this method :
public Bitmap getBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
view.layout(0, 0, view.getLayoutParams().width, view.getLayoutParams().height);
view.draw(canvas);
return returnedBitmap;
}

Null pointer on creating a Bitmap

I'm trying to screenshot a ScrollView and simply copy+pasted the solution from here: Taking a "screenshot" of a specific layout in Android . Unfortunately I'm getting a NP # Bitmap b = Bitmap.createBitmap(u.getDrawingCache());
My XML is
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/scrollingProfile"
android:layout_width="match_parent"
android:fillViewport="true"
android:layout_height="wrap_content"
android:background="#drawable/tile_tan_repeat">
<LinearLayout
android:id="#+id/paidLayoutLinearParent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!--......-->
</LinearLayout>
</ScrollView>
Anyone have any ideas of why this is happening? I've never really worked with saving files like this so debugging this code is pretty unfamiliar to me.
Thank you!
Edit:This is the code I'm using
public void onClick(View v) {
if(v.getId()==R.id.screenshot){//source: https://stackoverflow.com/questions/10650049/taking-a-screenshot-of-a-specific-layout-in-android
View u = findViewById(R.id.scrollingProfilePaid);
u.setDrawingCacheEnabled(true);
ScrollView z = (ScrollView) findViewById(R.id.scrollingProfilePaid);
int totalHeight = z.getChildAt(0).getHeight();
int totalWidth = z.getChildAt(0).getWidth();
u.layout(0, 0, totalWidth, totalHeight);
u.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(u.getDrawingCache());
u.setDrawingCacheEnabled(false);
//Save bitmap
String extr = Environment.getExternalStorageDirectory().toString() + File.separator + "Folder";
//String fileName = new SimpleDateFormat("yyyyMMddhhmm'profile.jpg'").format(new Date());
String fileName = "profile.jpg";
File myPath = new File(extr, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
just put the code inside
scrollview.post(
new Runnable()
{
#Override
public void run()
{
//this method will call after scrollview's onDraw method
// so the view is ready to generarte bitmap at this point
//put here your screen shot code
}
});

How to save an Image after drawing on it

I am using this tutorial for creating a drawing app in android.
What I am trying to do is get an image from gallery and then after painting on it, trying to save it.
After drawing, when I try to save the image it only saves the drawing with black background. The image taken from the gallery is not visible in saved image.
My Code:
XML Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFCCCCCC"
android:orientation="vertical"
tools:context=".ImageActivity" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/my_save_btn"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/save"
android:src="#drawable/save" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:id="#+id/my_view_drawing_pad1"
android:layout_marginBottom="3dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="3dp"
android:layout_weight="1" >
<LinearLayout
android:id="#+id/my_view_drawing_pad"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
</LinearLayout>
ImageActivity class:
public class ImageActivity extends Activity implements OnClickListener
{
private DrawingView drawView;
private ImageButton ibsaveBtn;
LinearLayout llDrawingPad;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
drawView = new DrawingView(this);
llDrawingPad = (LinearLayout) findViewById(R.id.my_view_drawing_pad);
ibsaveBtn = (ImageButton)findViewById(R.id.my_save_btn);
ibsaveBtn.setOnClickListener(this);
// code to get image from gallery ...
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
// getting the image
File file = new File(s);
if (file.exists()) {
fp = file.getAbsolutePath();
d = Drawable.createFromPath(file.getAbsolutePath());
drawView = new DrawingView(this);
llDrawingPad = (LinearLayout) findViewById(R.id.my_view_drawing_pad);
llDrawingPad.addView(drawView);
llDrawingPad.setBackgroundDrawable(d);
}
} // end onActivityResult
#Override
public void onClick(View view)
{
drawView.setDrawingCacheEnabled(true);
drawView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
String imgSaved = MediaStore.Images.Media.insertImage(
getContentResolver(), drawView.getDrawingCache(), UUID.randomUUID()
.toString() + ".png", "drawing");
if (imgSaved != null)
{
Toast savedToast = Toast.makeText(getApplicationContext(),
"Drawing saved to Gallery!", Toast.LENGTH_SHORT);
savedToast.show();
} else {
Toast unsavedToast = Toast.makeText(getApplicationContext(),
"Oops! Image could not be saved.", Toast.LENGTH_SHORT);
unsavedToast.show();
}
drawView.destroyDrawingCache();
} // end onClick
What am I missing here??
try eliminate this line
drawView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Try doing this in your onClick:
drawView = new DrawingView(this);
drawView.setDrawingCacheEnabled(true);
Bitmap bitmap = drawView.getDrawingCache();
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(path+"image.png");
FileOutputStream ostream;
try {
file.createNewFile();
ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.flush();
ostream.close();
Toast.makeText(getApplicationContext(), "image saved", 5000).show();
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "error", 5000).show();
}

writing app to take a screenshot, and then save it to the gallery of my Android phone, but the saved screenshot is completely black

Here is my Screenshot class. The app is saving the screenshot in my gallery, which is what I want, but the image is completely black! If you had any suggestions to make this work, they would be much appreciated! Thanks!
public class Screenshot extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// set event listener for the Save Contact Button
Button button =
(Button) findViewById(R.id.button);
button.setOnClickListener(buttonClicked);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.screenshot, menu);
return true;
}
// responds to event generated when user clicks the Done Button
OnClickListener buttonClicked = new OnClickListener()
{
#Override
public void onClick(View v)
{
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
}
};
public void saveBitmap(Bitmap bitmap) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.LinearLayout01);
Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(), mainLayout.getHeight(),
Bitmap.Config.ARGB_8888);
MediaStore.Images.Media.insertImage(getContentResolver(), b, "image.png" , "screenshot");
}
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
}
and here is my 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:id="#+id/button"
android:layout_height = "wrap_content"
android:layout_width ="wrap_content"
android:text = "take screenshot"
android:onClick = "DoIt"
/>
<ImageView
android:id="#+id/eiffelTowerImageView"
android:layout_width="200dip"
android:layout_height="200dip"
android:layout_toRightOf="#+id/colosseumImageView"
android:src="#drawable/eiffeltower" />
</LinearLayout>
This Code Works like a Charm for me
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;
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay()
.getHeight();
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
Log.e("Screenshot", "taken successfully");
return b;
}
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory()
+ "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
Log.e("Screenshot", "saved successfully");
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
Get Activity in OnCreate()
Activity activity = (MainActivity) this;
Then Call these Function where ever you want
Bitmap bitmap = takeScreenShot(activity);
saveBitmap(bitmap);
Your solution will only work for taking a screenshot of your own app (since it uses the app's drawing cache), so if that's what you want to do, you'll have to make sure it's visible on the screen. Anything that your app doesn't have permission to view (like another app running behind it) will not show up or, as you're seeing, will show up black.
I suggest you look at this other screenshot question here to see the constraints under which you're working. Primarily, since you presumably don't have root permissions or a signature application (which would only be true if you compiled your own ROM), then you can't capture the framebuffer, which is what the native Android screenshot mechanism in 4.0+ can do for you if you press a specific key combination (on my Galaxy Nexus it's power+volume down).
Try this code :
public class MainActivity extends Activity {
Button btn_shoot;
int i = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_shoot = (Button)findViewById(R.id.btn_shoot);
btn_shoot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = findViewById(R.id.relativelayout);
view = view.getRootView();
view.setDrawingCacheEnabled(true);
view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
Bitmap bitmap = view.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setBackgroundDrawable(bitmapDrawable);
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//we check if external storage is available, otherwise display an error message to the user
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/Tutorial_ScreenShot");
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/Tutorial_ScreenShot/screenshot" + i + ".jpg", Toast.LENGTH_SHORT).show();
i++;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
else
{
Toast.makeText(MainActivity.this, "SD Card not available!", Toast.LENGTH_SHORT).show();
}
}
});
}
}

Categories

Resources