当我的应用程序在后台运行时,我需要以编程方式获取Android设备或模拟器的屏幕截图,并每200毫秒保存一次图像到计算机上。我已经使用以下代码实现了该过程,但只能在我的应用程序在前台运行时工作。我希望在应用程序在后台运行时也能够截取屏幕截图。以下是我的代码:
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;
}
我如何在程序中实现设备 -> DDMS
屏幕截图的刷新和保存按钮功能?我能做到吗?