Android takes screenshots and saves them

  • 2020-11-30 08:34:13
  • OfStack

This article explains how to intercept the current screen on an Android phone or tablet and save the interception to a directory folder in SDCard.
The implementation code is as follows:


/** 
 *  Gets and saves a screenshot of the current screen  
 */ 
private void GetandSaveCurrentImage() 
{ 
 //1. build 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. Access to 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 has been saved to SDCard/AndyDemo/ScreenImage/ Under the ", Toast.LENGTH_LONG).show(); 
  } 
 
 } catch (Exception e) { 
  e.printStackTrace(); 
 } 
} 
 
 /** 
 *  To obtain SDCard Directory path function  
 * @return 
 */ 
private String getSDCardPath(){ 
 File sdcardDir = null; 
 // judge SDCard If there is a  
 boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); 
 if(sdcardExist){ 
  sdcardDir = Environment.getExternalStorageDirectory(); 
 } 
 return sdcardDir.toString(); 
} 

Since you are working on SDCard, don't forget to give SDCard read and write access in the manifest.xml file:


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

I hope this article has helped you learn Android software programming.


Related articles: