安卓截屏代码有许多方式,看了几个感觉有些复杂,有的用view的getCache方法,不知道能不截屏非当前view界面的图片,有些还要修改mk文件之类的,很是头大。
此处介绍一种简易的方式。需要手机已经root。第一次调用时会弹出对话框询问是否同意其使用权限。
代码如下:
/**
* take snapshot. need phone to be rooted
* @param strPath the pic path to save
* @return the real pic path
* @throws IOException
* @throws InterruptedException
*/
public static String takeSnapShoot(String strPath) throws IOException, InterruptedException {
if (strPath.isEmpty()){
strPath=String.format("/sdcard/%s.png",getCurTimeStr());
}
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + strPath).getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
return strPath;
}