android利用反射调用截屏api,Android利用反射机制调用截屏方法和获取屏幕宽高的方法...

想要在应用中进行截屏,可以直接调用 View 的 getDrawingCache 方法,但是这个方法截图的话是没有状态栏的,想要整屏截图就要自己来实现了。

还有一个方法可以调用系统隐藏的 screenshot 方法,来进行截屏,这种方法截图是整屏的。

通过调用 SurfaceControl.screenshot() / Surface.screenshot() 截屏,在 API Level 大于 17 使用 SurfaceControl ,小于等于 17 使用 Surface,但是 screenshot 方法是隐藏的,因此就需要用反射来调用这个方法。

这个方法需要传入的参数就是宽和高,因此需要获取整个屏幕的宽和高。常用的有三种方法。

获取屏幕宽高

方法一

int screenWidth = getWindowManager().getDefaultDisplay().getWidth();

int screenHeight = getWindowManager().getDefaultDisplay().getHeight();

这个方法会提示过时了,推荐后边两种。

方法二

DisplayMetrics dm = new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(dm);

int screenWidth = dm.widthPixels;

int screenHeight = dm.heightPixels;

方法三

Resources resources = this.getResources();

DisplayMetrics dm = resources.getDisplayMetrics();

int screenWidth = dm.widthPixels;

int screenHeight = dm.heightPixels;

反射调用截屏方法

public Bitmap screenshot() {

Resources resources = this.getResources();

DisplayMetrics dm = resources.getDisplayMetrics();

String surfaceClassName = "";

if (Build.VERSION.SDK_INT <= 17) {

surfaceClassName = "android.view.Surface";

} else {

surfaceClassName = "android.view.SurfaceControl";

}

try {

Class> c = Class.forName(surfaceClassName);

Method method = c.getMethod("screenshot", new Class[]{int.class, int.class});

method.setAccessible(true);

return (Bitmap) method.invoke(null, dm.widthPixels, dm.heightPixels);

} catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException | ClassNotFoundException e) {

e.printStackTrace();

}

return null;

}

最后返回的 Bitmap 对象就是截取得图像了。

需要的权限

调用截屏这个方法需要系统权限,因此没办法系统签名的应用是会报错的。

到此这篇关于Android利用反射机制调用截屏方法和获取屏幕宽高的方法的文章就介绍到这了,更多相关android 反射调用截屏方法内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值