我在我的一个机器人测试中尝试调用 content.setDrawingCacheEnabled(true) 时遇到了问题。当我尝试在上下文中启用绘图缓存时,有时会收到 CalledFromWrongThreadException。这似乎只在模拟器上运行时发生。当我在设备(Samsung S2)上尝试这个时,它每次都有效......
这是代码
调用函数:
String screnshotName = String.format("SS_Cities_%s.png", s);
File ssDir = Environment.getExternalStorageDirectory();
TestUtilities.takeScreenShot(solo.getCurrentActivity(), ssDir, screnshotName);
截图功能(抛出异常):
public static void takeScreenShot(Activity activity, File Directory, String FileName) throws Exception {
View content = activity.findViewById(R.id.content);
***// This is a horrible hack that i want to get rid of***
// Occasiaonally setDrawingCacheEnabled throws a CalledFromWrongThreadException
int MAX_RETRIES = 10;
for(int i = 0; i < MAX_RETRIES; i++)
{
try{
content.setDrawingCacheEnabled(true);
continue;
}
catch (Exception e){}
}
content.buildDrawingCache();
Bitmap b = content.getDrawingCache();
File outputFile = new File(Directory.toString() + "/" + FileName);
try {
if (!Directory.exists()) {
Directory.mkdirs();
}
if (!Directory.canWrite()) {
throw new Exception("Directory not writable");
}
FileOutputStream fos = new FileOutputStream(outputFile);
if (fos != null) {
b.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
}
} catch (Exception e) {
String screenshotError = String.format("Error taking screenshot: %s", e.toString());
throw new Exception(screenshotError);
}
}
我正在测试的应用程序中设置的权限:
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>