The instance code in Android to capture the current screen image

  • 2020-05-17 06:26:29
  • OfStack


/**
     *  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 file 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 operating on SDCard, don't forget to assign read and write access to SDCard in the manifest.xml file:

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


Related articles: