以编程方式在Android设备上保存文件

问题描述:

我正在编写一些UI测试,我需要能够通过编程的方式让这些测试在特定时间点对我的应用程序进行截图。我真的不知道如何从UI测试中截取屏幕截图,但我已经明白了这一点,并稍微修改了一些我在网上找到的用于我的目的的代码。据我所知,截图的代码工作正常,然而,我似乎无法保存屏幕截图,一旦我把它。以编程方式在Android设备上保存文件

我发现的代码似乎使用以下步骤来保存屏幕截图。当然,它不起作用,就像我说的那样,但这可能是因为我的设备是Nexus 7,根据我读到的内容,存储在该设备上的工作方式与在其他Android设备上的工作方式不同,尽管没有一个我所看到的资源已经详细报道了这种差异。

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + theFileName; 
File imageFile = new File(path); 

下一位是在try-catch块中,并且此时程序会引发FileNotFound异常。

out = new FileOutputStream(imageFile); 

( “走出去” 是一个FileOutputStream)

我认为Environment.getExternalStorageDirectory()。getAbsolutePath()不返回正确路径或东西。我也尝试过只是.getPath,但那也不起作用。在定义之前,我已经检查过imageFile的文件路径是否正确,并且它是“/ storage/emulated/0/screenname”(其中screenname是代码中的文件名)。

我需要将屏幕截图保存在某个设备上。只要我可以从我的计算机*问它,这并不重要,但是如果我可以以这种方式对其进行编码以便我可以在任何设备上运行程序而无需重写代码用于确定路径。如果这是不可能的,我希望它至少在我的Nexus 7上工作。

任何有关如何能做到这一点的建议,将不胜感激。谢谢!

编辑:清单文件

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <activity 
     android:name=".DisplayMessageActivity" 
     android:label="@string/title_activity_display_message" 
     android:parentActivityName=".MainActivity" > 
     <meta-data 
      android:name="android.support.PARENT_ACTIVITY" 
      android:value="com.example.john.johntest.MainActivity" /> 
    </activity> 
</application> 

+0

您在清单文件中有WRITE_EXTERNAL_STORAGE权限请求吗? – greenapps 2015-02-23 20:33:11

+0

这样做会使我的应用程序显然停止运行。它开始将文件上传到我的设备,并没有得到任何进一步的。 – ThisIsAName12345 2015-02-23 21:10:08

+0

将哪个文件上传到您的设备?你在说什么?更好地显示使用的代码。 – greenapps 2015-02-23 22:28:11

把你的清单文件WRITE_EXTERNAL_STORAGE许可请求。

+0

对于任何人可能来看,代码是: ThisIsAName12345 2015-02-24 16:47:14