您的位置:首页 > 移动开发 > Android开发

Android截图的两种方法

2016-03-03 18:53 411 查看
转载请注明出处:/article/8521424.html

有时候我们需要保存某个Activity的截图,下面介绍两种方法。

1)使用view的getDrawingCache来获取当前Activity的截图

<strong> </strong> private static String TAG = "--->";
private static final String SCREEN_SHOT_DIR = "TestScreenShot";
private static String FILE_NAME_PRE = "ScreenShot";
// 获取指定Activity的截屏,保存到png文件

/**
* @param activity
* @return
*/
@SuppressWarnings("deprecation")
private static Bitmap takeScreenShot(Activity activity) {
// View是你需要截图的View,这样保存的是当前APP的整个截图,因此使用DecorView,如果是某个子控件,可以通过findViewById找到对应的View
View view = activity.getWindow().getDecorView();
boolean isCacheEnable = view.isDrawingCacheEnabled();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
// 获取状态栏高度
Rect frameRect = new Rect();
view.getWindowVisibleDisplayFrame(frameRect);
int statusBarHeight = frameRect.top;
// 获取屏幕长和高
int width;
int height;
Display display = activity.getWindowManager().getDefaultDisplay();
if (Build.VERSION.SDK_INT > 12) {
Point point = new Point();
display.getSize(point);
width = point.x;
height = point.y;
} else {
width = display.getWidth();
height = display.getHeight();
}
// 去掉标题栏,DecorView是不包含标题栏的
Bitmap bmpScreenshot = Bitmap.createBitmap(bmp, 0,
statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
view.setDrawingCacheEnabled(isCacheEnable);
return bmpScreenshot;
}

//保存指定View的截图,与保存Activity的截图类似
public static Bitmap screenshot(View view) {
if (view == null) {
Log.w(TAG, "screenshot:view is null");
return null;
}
boolean isCacheEnable = view.isDrawingCacheEnabled();
view.setDrawingCacheEnabled(true);
Bitmap bmp = view.getDrawingCache();
try {
saveScreenShot(bmp, "");
} catch (Exception e) {
e.printStackTrace();
} finally {
view.destroyDrawingCache();
view.setDrawingCacheEnabled(isCacheEnable);
}
return bmp;
}


如果要将图片写到SD卡,所以记得申请对应的权限。

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


下面给出将Bitmap保存到文件的代码:

<pre name="code" class="java">// 保存到sdcard

/**
* @param bitmap      :当前屏幕的位图数据
* @param strFileName :截图保存文件位置
*/
public static void saveScreenShot(Bitmap bitmap, String fileDirStr)
throws Exception {
FileOutputStream fos = null;
File file = null;
String filePath = fileDirStr;
if (fileDirStr == null || fileDirStr.trim().length() == 0) {
filePath = Environment.getExternalStorageDirectory() + "/"
+ SCREEN_SHOT_DIR;
file = new File(filePath);
} else {
file = new File(fileDirStr);
}
if (!file.exists()) {
if (!file.mkdir()) {
Log.e(TAG, "create folder failed ");
throw new FileNotFoundException(
"can't create screenShot folder");
} else {
Log.i(TAG, "create folder successful");
}
}
filePath = filePath + "/" + generateFileName() + ".png";
fos = new FileOutputStream(filePath);
if (null != fos) {
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
try {
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.close();
}
Log.i(TAG, "screen shot complete");
}
}

//根据当前时间生成文件名
public static String generateFileName() {
String filename = null;
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int millisecond = calendar.get(Calendar.MILLISECOND);
filename = FILE_NAME_PRE + "-" + year + "-" + month + "-"
+ day + "-" + hour + "-" + minutes + "-" + second + "-"
+ millisecond;
return filename;
}



2)使用系统提供的截图命令来截图,需要APP有root权限

<pre name="code" class="java">public static int sys_screenshot_root(String filePath) {
if (filePath == null || filePath.length() == 0) {
filePath = Environment.getExternalStorageDirectory() + "/"
+ SCREEN_SHOT_DIR + generateFileName() + ".png";
}
if (!isRooted()) {
return ERR_NOT_ROOT;
}
Process process = null;
PrintStream outputStream = null;
int exp_code = 0;
try {
process = Runtime.getRuntime().exec("su");
outputStream = new PrintStream(new BufferedOutputStream(
process.getOutputStream(), 8192));
if (Build.VERSION.SDK_INT >= 9)// android 2.4 & above
{
outputStream.println("/system/bin/screencap -p " + filePath);// screenshot  -xx.png
} else if (Build.VERSION.SDK_INT >= 9)// android 2.3 & above
{
Log.i(TAG, "not support");
}
outputStream.flush();
if (outputStream != null) {
outputStream.close();
}
process.waitFor();
} catch (NullPointerException e) {
exp_code = ERR_NULLPNT_EXP;
} catch (IOException e) {
exp_code = ERR_IO_EXP;
} catch (InterruptedException e) {
exp_code = ERR_INTR_EXP;
} finally {
if (outputStream != null) {
outputStream.close();
}
if (process != null) {
process.destroy();
}
}
return exp_code;
}

// 判断是否具有ROOT权限
public static boolean isRooted() {
boolean res = false;
try {
if ((!new File("/system/bin/su").exists())
&& (!new File("/system/xbin/su").exists())) {
res = false;
} else {
res = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return res;
}

public static final int ERR_INTR_EXP = 1;
public static final int ERR_IO_EXP = 2;
public static final int ERR_NULLPNT_EXP = 3;
public static final int ERR_NOT_ROOT = 4;




两种方法各有优缺点,第1)种不需要root,而且可以用来保存某个子View的截图,但是不能保存整个手机界面的截图;第2)方法可以保存整个手机界面的截图,但是需要root
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: