This article describes how to capture the current screen on an Android phone or tablet and save the captured screen to a directory folder in the SDCard. The implementation code is as follows:
[Html]
/**
* Get and save the current screen
*/
Private void GetandSaveCurrentImage ()
{
// 1. Construct a Bitmap
WindowManager windowManager = getWindowManager ();
Display display = windowManager. getDefaultDisplay ();
Int w = display. getWidth ();
Int h = display. getHeight ();
Bitmap Bmp = Bitmap. createBitmap (w, h, Config. ARGB_8888 );
// 2. Obtain the screen
View decorview = this. getWindow (). getDecorView ();
Decorview. setDrawingCacheEnabled (true );
Bmp = decorview. getDrawingCache ();
String SavePath = getSDCardPath () + "/AndyDemo/ScreenImage ";
// 3. Save Bitmap
Try {
File path = new File (SavePath );
// File
String filepath = SavePath + "/Screen_1.png ";
File file = new File (filepath );
If (! Path. exists ()){
Path. mkdirs ();
}
If (! File. exists ()){
File. createNewFile ();
}
FileOutputStream fos = null;
Fos = new FileOutputStream (file );
If (null! = Fos ){
Bmp. compress (Bitmap. CompressFormat. PNG, 90, fos );
Fos. flush ();
Fos. close ();
Toast. makeText (mContext, "The screenshot file has been saved to SDCard/AndyDemo/ScreenImage/", Toast. LENGTH_LONG). show ();
}
} Catch (Exception e ){
E. printStackTrace ();
}
}
/**
* Get the directory path of SDCard
* @ Return
*/
Private String getSDCardPath (){
File sdcardDir = null;
// Determine whether an SDCard exists
Boolean sdcardExist = Environment. getExternalStorageState (). equals (android. OS. Environment. MEDIA_MOUNTED );
If (sdcardExist ){
SdcardDir = Environment. getExternalStorageDirectory ();
}
Return sdcardDir. toString ();
}
To perform operations on SDCard, do not forget to grant the read and write permissions to SDCard in the manifest. xml file:
[Html]
<Uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/>
From Android-Idea