Android take screen shot programmatically
Solution 1:
Here you go...I used this:
View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File myPath = new File(extr, getString(R.string.free_tiket)+".jpg");
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();
}
v iz root layout...just to point ;)))
Solution 2:
For the next reader of this question-
The very simple way to do this by drawing your view to canvas-
pass your main layout reference to this method-
Bitmap file = save(layout);
Bitmap save(View v)
{
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
Solution 3:
I think you have to wait until the layout is drawn completely..Use ViewTreeObserver to get a call back when layout is drawn completely..
On your onCreate add this code..Only call getScreen from inside onGlobalLayout()..
ViewTreeObserver vto = content.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
content.getViewTreeObserver().removeGlobalOnLayoutListener(this);
getScreen();
}
});
I asked a somewhat similiar question once..Please see my question which explains the way to take screenshot in android..Hope this helps
Solution 4:
public class MainActivity extends Activity
{
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
}
});
}
public Bitmap takeScreenshot()
{
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
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);
fos.flush();
fos.close();
}
catch (FileNotFoundException e)
{
Log.e("GREC", e.getMessage(), e);
}
catch (IOException e)
{
Log.e("GREC", e.getMessage(), e);
}
}
}
don't forgot to give write external storage permission!