安卓 - 如何以编程方式截取屏幕截图
我需要以编程方式在应用程序安装并在后台运行每 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