安卓截屏初体验

工作需要,需要后台服务去定时截取前台显示app的画面。百度一下,网上很多例程,以为很简单,然并卵,一路踩坑。。。

踩坑一:使用View.getDrawingCache()方法

View dView = getWindow().getDecorView();
dView.setDrawingCacheEnabled(true);
dView.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(dView.getDrawingCache());
if (bitmap != null) {
  try {
    // 获取内置SD卡路径
    String sdCardPath = Environment.getExternalStorageDirectory().getPath();
    // 图片文件路径
    String filePath = sdCardPath + File.separator + "screenshot.png";
    File file = new File(filePath);
    FileOutputStream os = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
    os.flush();
    os.close();
    DebugLog.d("a7888", "存储完成");
  } catch (Exception e) {
  }
}

写了个demo,可以截屏,兴冲冲的以为搞定了,集成的时候才发现,这个只能抓取本应用的画面,失败。不过也算是学到了,通过该方法可以截取本应用的画面,或者截取指定控件的画面。

踩坑二:使用screencap -p指令

publicvoid takeScreenShot(){ 
  String mSavedPath = Environment.getExternalStorageDirectory()+File. separator + "screenshot.png" ; 
try {           
      Runtime. getRuntime().exec("screencap -p " + mSavedPath); 
  } catch (Exception e) { 
      e.printStackTrace(); 
  }

代码很简单,有两个注意点,一是权限,
(1). 在AndroidManifest.xml文件中添加

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

(2). 修改APK为系统权限,将APK放到源码中编译, 修改Android.mk

LOCAL_CERTIFICATE := platform

写了个demo,可以截屏,兴冲冲的以为搞定了,结果又是想多了,截图的时间太长了,全屏截图一次需要1s+,还要再想办法。
第二点是指令中如果有一些特殊字符会导致指令运行失败,如“|”、“>>”等,需要使用以下接口:

Runtime.getRuntime().exec( new String[]{"/bin/sh","-c",cmd},null);

踩坑三:通过反射使用隐藏接口android.view.SurfaceControl.screenshot

 try {
            DisplayMetrics mDisplayMetrics = new DisplayMetrics();
            float[] dims = { mDisplayMetrics.widthPixels,mDisplayMetrics.heightPixels };
            Class<?> demo = null;
            demo = Class.forName("android.view.SurfaceControl");
            Method method=demo.getMethod("screenshot",new Class[]{Rect.class,int.class,int.class,int.class});
            Bitmap mScreenBitmap = (Bitmap) method.invoke(null,new Rect(),(int) dims[0],(int) dims[1],0);
            mScreenBitmap.recycle();
        } catch (Exception e) {
            e.printStackTrace();
        }

(1). 在AndroidManifest.xml文件中添加

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

(2). 修改APK为系统权限,将APK放到源码中编译, 修改Android.mk

LOCAL_CERTIFICATE := platform

同样要添加权限。同样一堆坑需要注意,一通过调用SurfaceControl.screenshot() / Surface.screenshot() 截屏,在 API Level 大于 17 使用 SurfaceControl ,小于等于 17 使用 Surface。二"screenshot"还是的参数不同版本不同,当系统提示找不到这个函数的时候,去系统中找下这个文件,看下这个版本的是什么接口,文件路径/frameworks/base/core/java/android/view/SurfaceControl.java。

写了个demo,可以截屏,帧率也可以,终于搞定了‘——’

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值