该篇文章是说明在android手机或平板电脑中如何实现截取当前屏幕的功能,并把截取的屏幕保存到sdcard中的某个目录文件夹下面。
实现的代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
/**
* 获取和保存当前屏幕的截图
*/
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();
}
} 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的读写权限:
1
|
<uses-permission android:name= "android.permission.write_external_storage" />
|
希望本文所述对大家学习android软件编程有所帮助。