This method is to get the screen shots of current activity through view, not framebuffer way, so there are some limitations. But this method is relatively simple and easy to understand.
Get a screenshot of the bitmap format first by using the following function:
Copy Code code as follows:
Public Bitmap myshot (activity activity) {
Get the top view in Windows
View view = Activity.getwindow (). Getdecorview ();
View.builddrawingcache ();
Get status bar height
Rect Rect = new Rect ();
View.getwindowvisibledisplayframe (rect);
int statusbarheights = Rect.top;
Display display = Activity.getwindowmanager (). Getdefaultdisplay ();
Get screen width and height
int widths = Display.getwidth ();
int heights = Display.getheight ();
Allow the current window to save cached information
View.setdrawingcacheenabled (TRUE);
Remove status bar
Bitmap bmp = Bitmap.createbitmap (View.getdrawingcache (), 0,
Statusbarheights, widths, heights–statusbarheights);
Destroying cached information
View.destroydrawingcache ();
return BMP;
}
After you get the picture in the bitmap format, you can save it to the SD card, or you can display it directly to the ImageView in the following way:
Copy Code code as follows:
Convert Bitmap to Drawable
Bitmapdrawable bd=new bitmapdrawable (Myshot ());
Imageview.setbackgrounddrawable (BD);
Imageview.setimagebitmap (Myshot ());
If you want to write to a save in SD, you can use the following method:
Copy Code code as follows:
private void Savetosd (Bitmap bmp, String dirname,string fileName) throws IOException {
Determine if the SD card exists
if (Environment.getexternalstoragestate (). Equals (
environment.media_mounted)) {
File dir = new file (dirname);
To determine if a folder exists, if it does not exist, create
if (!dir.exists ()) {
Dir.mkdir ();
}
File File = new file (dirname + fileName);
To determine if a file exists, if it does not exist, create
if (!file.exists ()) {
File.createnewfile ();
}
FileOutputStream fos = null;
try {
FOS = new FileOutputStream (file);
if (FOS!= null) {
The first parameter is the picture format, the second is the picture quality, the third is the output stream
Bmp.compress (Bitmap.CompressFormat.PNG, FOS);
Run out of close
Fos.flush ();
Fos.close ();
}
catch (FileNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
DirName is the output of the folder name, Filaname is the output of the file name, the two together form the output path, such as "/mnt/sdcard/pictures/shot.png." Also be aware of registering write permissions in Androidmanifest:
Copy Code code as follows:
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>