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

时间:2015-02-23 20:21:37

标签: android file save screenshot

我正在编写一些UI测试,我需要能够以编程方式在某些点上获取我的应用程序的屏幕截图。我不确定如何从UI测试中截取屏幕截图,但是我已经想到并且稍微修改了我在网上找到的一些代码以便为我的目的工作。据我所知,截图的代码工作得很好;但是,一旦我接受它,我似乎无法保存屏幕截图。

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

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

下一个位在try-catch块中,此时程序会抛出FileNotFound异常。

out = new FileOutputStream(imageFile);

(" out"是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>

1 个答案:

答案 0 :(得分:0)

在清单文件中放置WRITE_EXTERNAL_STORAGE权限请求。