当前位置: 移动技术网 > 移动技术>移动开发>Android > Android实现截屏并保存操作功能

Android实现截屏并保存操作功能

2019年07月24日  | 移动技术网移动技术  | 我要评论

该篇文章是说明在android手机或平板电脑中如何实现截取当前屏幕的功能,并把截取的屏幕保存到sdcard中的某个目录文件夹下面。
实现的代码如下:

/** 
 * 获取和保存当前屏幕的截图 
 */ 
private void getandsavecurrentimage() 
{ 
 //1.构建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.获取屏幕 
 view decorview = this.getwindow().getdecorview();  
 decorview.setdrawingcacheenabled(true);  
 bmp = decorview.getdrawingcache();  
  
 string savepath = getsdcardpath()+"/andydemo/screenimage"; 
 
 //3.保存bitmap  
 try { 
  file path = new file(savepath); 
  //文件 
  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, "截屏文件已保存至sdcard/andydemo/screenimage/下", toast.length_long).show(); 
  } 
 
 } catch (exception e) { 
  e.printstacktrace(); 
 } 
} 
 
 /** 
 * 获取sdcard的目录路径功能 
 * @return 
 */ 
private string getsdcardpath(){ 
 file sdcarddir = null; 
 //判断sdcard是否存在 
 boolean sdcardexist = environment.getexternalstoragestate().equals(android.os.environment.media_mounted); 
 if(sdcardexist){ 
  sdcarddir = environment.getexternalstoragedirectory(); 
 } 
 return sdcarddir.tostring(); 
} 

由于要对sdcard进行操作,所以别忘记了在manifest.xml文件中赋以对sdcard的读写权限:

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

希望本文所述对大家学习android软件编程有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网