How to programmatically take a screenshot on Android?


First of All you need to add WRITE_EXTERNAL_STORAGE permission in your Android manifest since will be writing to the external storage.To write to the external storage, we must request the WRITE_EXTERNAL_STORAGE permission in your manifest file.

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


Bitmap bitmap; //Create a bitmap object
/* android.graphics.Bitmap - http://developer.android.com/reference/android/graphics/Bitmap.html */
  View scrView = findViewById(R.id.root); 
 // Select the view
  scrView.setDrawingCacheEnabled(true); 
  bitmap = Bitmap.createBitmap(scrView.getDrawingCache()); 
//returns an immutable bitmap from source bitmap
  scrView.setDrawingCacheEnabled(false);


  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
// http://developer.android.com/reference/java/io/ByteArrayOutputStream.html
  bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//Write a compressed version of the bitmap to the specified outputstream.
  File file = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "ScrShot.jpg")
//Constructs a new file using the specified path.
  file.createNewFile();
//Creates a new, empty file on the file system according to the path information stored in this file.
  FileOutputStream fOut = new FileOutputStream(file);
/*  An output stream that writes bytes to a file. If the output file exists, it can be replaced or appended to. If it does not exist, a new file will be created. */
  fOut.write(bytes.toByteArray()); 
  fOut.close(); //make sure to close OutputStream.

Comments

Popular posts from this blog

Privacy Policy - Gauraw_Yadav

Android System Information

Photo Effects Powered By Adviary SDK