Programmatic screenshot on android: setDrawingCacheEnabled throws a CalledFromWrongThreadException
I'm running into an issue when trying to call content.setDrawingCacheEnabled(true) in one of my robotium tests. When i try to enable the drawing cache on the context I sometimes get a CalledFromWrongThreadException. This only seems to happen when running on an emulator. When I try this on device (Samsung S2) it works every time...
Here is the code
Calling function:
String screnshotName = String.format("SS_Cities_%s.png", s);
File ssDir = Environment.getExternalStorageDirectory();
TestUtilities.takeScreenShot(solo.getCurrentActivity(), ssDir, screnshotName);
Screenshot function (that throws exception):
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 outpu开发者_运维知识库tFile = 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);
}
}
Permissions set in the application I'm testing:
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Android emulator doesn't always work fine with external storage. That's why you might get those errors. So I suggest that whenever you want to test apps that use external storage you do it in a real device since you won't have all the "unfixed" errors that the emulator still has.
I can't see whether you perform your takeScreenShot method from the UIThread or not but as far as I can see I think your question is being answered here:
StackOverflow: CalledFromWrongThreadException
精彩评论