This method is to obtain screenshots of the current activity through view, not framebuffer, so it has certain limitations. But this method is relatively simple and easy to understand.
First, use the following function to obtain the screenshot of Bitmap format:
Copy the codeThe code is as follows:
public Bitmap myShot(Activity activity) {
// Get the top view in windows
View view = ().getDecorView();
();
// Get the status bar height
Rect rect = new Rect();
(rect);
int statusBarHeights = ;
Display display = ().getDefaultDisplay();
// Get screen width and height
int widths = ();
int heights = ();
// Allow the current window to save cache information
(true);
// Remove the status bar
Bitmap bmp = ((), 0,
statusBarHeights, widths, heights – statusBarHeights);
// Destroy cache information
();
return bmp;
}
After obtaining the bitmap format image, you can save it to the SD card or directly display it on the ImageView in the following way:
Copy the codeThe code is as follows:
// Convert bitmap to drawable
BitmapDrawable bd=new BitmapDrawable(myShot());
(bd);
(myShot());
If you want to write to SD to save, you can use the following method:
Copy the codeThe code is as follows:
private void saveToSD(Bitmap bmp, String dirName,String fileName) throws IOException {
// Determine whether the SD card exists
if (().equals(
Environment.MEDIA_MOUNTED)) {
File dir = new File(dirName);
// Determine whether the folder exists, and create it if it does not exist.
if(!()){
();
}
File file = new File(dirName + fileName);
// Determine whether the file exists, and create it if it does not exist.
if (!()) {
();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (fos != null) {
// The first parameter is the picture format, the second is the picture quality, and the third is the output stream
(, 100, fos);
// Close after use
();
();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
();
} catch (IOException e) {
// TODO Auto-generated catch block
();
}
}
}
dirName is the output folder name, filaName is the output file name, and the two together form the output path, such as "/mnt/sdcard/pictures/". Also note that you register write permissions in AndroidManifest:
Copy the codeThe code is as follows:
<uses-permission android:name=”.WRITE_EXTERNAL_STORAGE” />