2011-09-26 65 views
5

我一直在嘗試獲取屏幕截圖,但是在api level 8的android模擬器中創建了所有文件夾。我提到了下面的代碼。無法在android上使用robotium和私有方法拍屏幕截圖

在這段代碼中方法takeScreenShot()應該創建一個目錄並存儲圖像,同時作爲android junit testcase執行我得到的結果爲100%但不是文件夾不創建,屏幕截圖未被存儲。我應該根據我的手機使用其SD卡嗎?

public class NewRobotiumTest extends ActivityInstrumentationTestCase2 { 
...... 
...... 

    // actual testcase 

    public void testRecorded() throws Exception { 
     solo.waitForActivity("com.botskool.DialogBox.DialogBox", 
       ACTIVITY_WAIT_MILLIS); 
     solo.clickOnButton("Show Alert"); 
     solo.clickOnButton("Ok"); 
     solo.clickOnButton("Show Yes/No"); 
     takeScreenShot(solo.getViews().get(0), "testRecorded_1316975601089"); 
     solo.sleep(2000); 
     solo.clickOnButton("Yes"); 
     solo.clickOnButton("Show List"); 
     solo.clickOnScreen(118f, 563f); 

    } 

    /** 
    * I have added this to the android-manifest.xml file 
    * 
    * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    * 
    */ 

    public void takeScreenShot(final View view, final String name) 
      throws Exception { 

     getActivity().runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       view.setDrawingCacheEnabled(true); 
       view.buildDrawingCache(); 
       Bitmap b = view.getDrawingCache(); 
       FileOutputStream fos = null; 
       try { 
        final String path = Environment.getExternalStorageDirectory()+ "/test-screenshots/"; 
        File dir = new File("/mnt/sdcard/test-screenshots"); 
        if(!dir.mkdirs()){ 
         System.out.println("Creaet sd card failed"); 
        } 

        if (!dir.exists()) { 
         System.out.println(path); 
         dir.mkdirs(); 
        } 

        fos = new FileOutputStream(path + name + ".jpg"); 
        if (fos != null) { 
         b.compress(Bitmap.CompressFormat.JPEG, 90, fos); 
         fos.close(); 
        } 
       } catch (IOException e) { 
       } 
      } 
     }); 

    } 

} 

回答

7

您需要添加權限才能在主應用程序中寫入SD卡。不是JUnit測試項目! 這個添加到項目清單: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

相關問題