【问题标题】:Open file with certain extension Android打开具有特定扩展名 Android 的文件
【发布时间】:2013-08-26 16:30:32
【问题描述】:

我正在尝试制作一个允许用户在单击时打开并查看 .stl 文件的应用程序。通过将以下意图过滤器添加到我的 AndroidManifest.xml 中,我已经设法将此类文件与我的应用程序相关联: <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="file" /> <data android:mimeType="*/*" /> <data android:pathPattern=".*\\.STL" /> <data android:host="*" /> </intent-filter> 因此,当用户单击 .STL 文件时,我的应用程序就会启动。我被困在这里,因为我不知道如何将文件实际显示到我的应用程序中。有人可以帮忙吗? 谢谢

【问题讨论】:

    标签: android android-intent view


    【解决方案1】:

    您可以通过以下方式读取文件的内容:在您向intent-filter 注册的Activity 中:

    public class MyActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Uri data = getIntent().getData();
            try {
                String fileContents = getFileContents(data);
                Toast.makeText(getApplicationContext(), fileContents, Toast.LENGTH_LONG);
            } catch(IOException e) {
                // Handle error...
            }
        }
        private String getFileContents(Uri data) throws IOException {
            InputStream fileContents = getContentResolver().openInputStream(data);
            StringWriter writer = new StringWriter();
            IOUtils.copy(fileContents, writer, "US-ASCII");
            return writer.toString();
        }
        ...
    }
    

    这会将.stl 文件的内容读入变量fileContents 并在弹出窗口中显示。该代码使用来自the Apache Commons IO libraryIOUtils 类。为了将这个类集成到您的应用程序中,您需要下载 Commons IO 库的 jar 并将其复制到您的应用程序的 libs/ 文件夹中。

    【讨论】:

    • 谢谢你的回答,但是我还有一个问题:吐司没有出现。我将代码添加到 MainActivity 中,并且在 Manifest 文件中有以下条目:&lt;activity android:name=".MainActivity" android:label="@string/app_name"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.VIEW" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;category android:name="android.intent.category.BROWSABLE" /&gt; &lt;data android:scheme="file" /&gt; &lt;data android:mimeType="*/*" /&gt; &lt;data android:pathPattern=".*\\.STL" /&gt; &lt;data android:host="*" /&gt; &lt;/intent-filter&gt;
    猜你喜欢
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    相关资源
    最近更新 更多