转载请注明出处:http://blog.csdn.net/fishle123/article/details/50790835

有时候我们需要保存某个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

更多相关文章

  1. Android初级教程短信防火墙
  2. android之退出应用程序
  3. 记录Android中使用ViewDragHelper实现拖动View滑动的方法
  4. weex和Android的交互
  5. Android动画点击不运行
  6. android 保存 用户名和密码 设置等应用信息优化
  7. 【Dialer】自定义暗码进入测试模式
  8. Android(安卓)-- 基础
  9. 《Android(安卓)uiautomatorviewer不能截图》

随机推荐

  1. Android各个版本对应的源代码
  2. Android(安卓)Widget开发系列(二)
  3. android N 编译环境搭建
  4. 鸿蒙开发TV软件环境搭建以及简单教程
  5. android程序执行adb shell命令
  6. 详解Android(安卓)App AllowBackup配置带
  7. android使用util工具包
  8. android opensource webs
  9. android 短信拦截
  10. Android逆向基础之Dalvik指令集