1

我在我的一个机器人测试中尝试调用 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"/>
4

2 回答 2

1

Android 模拟器并不总是与外部存储一起正常工作。这就是为什么您可能会收到这些错误。所以我建议无论何时你想测试使用外部存储的应用程序,你都可以在真实设备中进行,因为你不会遇到模拟器仍然存在的所有“未修复”错误。

于 2011-11-15T19:10:24.990 回答
0

我看不到您是否从 UIThread 执行 takeScreenShot 方法,但据我所知,我认为您的问题在这里得到了回答:

StackOverflow:CalledFromWrongThreadException

于 2012-11-30T15:48:51.390 回答