我需要每200毫秒在后台安装并运行我的应用程序时,以编程方式对Android设备或模拟器的屏幕截图进行截图,并将图像保存在计算机中。我已经使用下面的代码实现了此过程,并且仅在我的应用程序处于前台时才起作用。我也想在我的应用程序处于后台时拍摄屏幕截图。下面是我的代码:
public static Bitmap takeScreenshot(Activity activity, int ResourceID) {
Random r = new Random();
int iterator=r.nextInt();
String mPath = Environment.getExternalStorageDirectory().toString() + "/screenshots/";
View v1 = activity.getWindow().getDecorView().findViewById(ResourceID);
v1.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
v1.layout(0, 0, v1.getMeasuredWidth(), v1.getMeasuredHeight());
v1.setDrawingCacheEnabled(true);
final Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
Bitmap resultBitmap = Bitmap.createScaledBitmap(bitmap, 640, 480, false);
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
imageFile.mkdirs();
imageFile = new File(imageFile+"/"+iterator+"_screenshot.png");
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
resultBitmap.compress(CompressFormat.PNG, 100, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(imageFile);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
如何以Devices -> DDMS
编程方式实现Screencapture的“刷新”和“保存”按钮的功能?我能做到吗?
如果您的手机已扎根,请尝试此操作
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
然后将img.png读取为位图,并将其转换为jpg,如下所示
Bitmap screen = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+
File.separator +"img.png");
//my code for saving
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
screen.compress(Bitmap.CompressFormat.JPEG, 15, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()+ File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
如果您的应用程序是在后台运行的,除非您是root用户,否则您将无法访问该屏幕,即使您在后台运行,以上代码也可以最有效地捕获任何屏幕的屏幕截图。
更新
Google尝试了一个库,您可以在不生根的情况下使用它来截取屏幕截图,但是我敢保证它会尽快耗尽内存。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句