利用反射截屏,需要root
查了不少资料,发现截屏这个理所当然的常见功能,想实现还是很费劲的,这应该谷歌是出于安全的考虑做出的限制吧。
这里列举了一些方法:
http://www.cnblogs.com/android100/p/Android-cut-screen.html
别的我没试,我只试了试反射的方法。
环境:
下面是代码:
public void screenshot() {
DisplayMetrics mDisplayMetrics = new DisplayMetrics();
float[] dims = {mDisplayMetrics.widthPixels,
mDisplayMetrics.heightPixels};
Class<?> demo = null;
try {
demo = Class.forName("android.view.SurfaceControl");
} catch (Exception e) {
e.printStackTrace();
}
try {
Method method = demo.getMethod("screenshot", new Class[]{int.class, int.class});
mScreenBitmap = (Bitmap) method.invoke(null, (int) dims[0], (int) dims[1]);
if (mScreenBitmap != null) {
mIvShow.setImageBitmap(mScreenBitmap);
}
if (mScreenBitmap != null) {
saveBitmap(mScreenBitmap, new File(Environment.getExternalStorageDirectory().getPath() + "/" + "AAAABBBB.png"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean saveBitmap(Bitmap bitmap, File file) {
if (bitmap == null)
return false;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
上面的代码,还是截不到屏幕的,还需要在Manifest.xml里添加一行:
android:sharedUserId=”android.uid.system”
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.screencapture"
android:sharedUserId="android.uid.system">
...
然后,运行,截图成功。
未root设备测试
在已经root的华为荣耀4X上测试成功之后,我用未root的360 F4高配版实验了一下,发现安装时提示INSTALL_FAILED_SHARED_USER_INCOMPATIBLE。这应该是在Manifest.xml里添加的android:sharedUserId=”android.uid.system”导致的。
在一片博客里:http://blog.csdn.net/happyhell/article/details/5903389,有关于这个错误的描述,主要是由于使用了android.uid.shared导致的问题。
需要在Android系统源码的环境下用make来编译,修改Android.mk文件,加入LOCAL_CERTIFICATE := platform这行。时间原因,暂时没法验证。有空了试试。