我在我的一个机器人测试中尝试调用content.setDrawingCacheEnabled(true)时遇到了问题。当我尝试在上下文中启用绘图缓存时,有时会获得CalledFromWrongThreadException。这似乎只在模拟器上运行时发生。当我在设备(三星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"/>
答案 0 :(得分:1)
Android模拟器并不总能与外部存储配合使用。这就是为什么你可能会得到这些错误。因此,我建议每当您想要测试使用外部存储的应用时,您都可以在真实设备中进行测试,因为您不会拥有仿真器仍然存在的所有“未修复”错误。
答案 1 :(得分:0)
我无法看到你是否从UIThread执行你的takeScreenShot方法,但据我所知,我认为你的问题在这里得到解答: