The function of capturing the current screen in Android

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.