Android - 允许用户使用app打开文本文件

时间:2012-10-18 19:51:10

标签: android android-intent android-manifest

我在http://www.vogella.com链接的帮助下解决了我的问题并进一步搜索。

•Android Manifest:          

<uses-sdk android:minSdkVersion="8" />
<supports-screens android:resizeable="true" android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:anyDensity="true" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" android:process="IPP.EZPadd">
    <activity
        android:label="@string/app_name"
        android:name=".EZPaddActivity" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter >
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:scheme="file" />
            <data android:mimeType="text/plain" />
        </intent-filter>
    </activity>
</application>

•Java活动:

public void open_on_start()
    {
        Intent i = getIntent();
        Uri data = i.getData();
        if (data == null)
        {
            return;
        }
        URL url;
        String startFile = "";
        try
        {
            url = new URL(data.getScheme(), data.getHost(), data.getPath());
            startFile = url.toString().replace("file:", "");
        }
        catch (Exception ex)
        {
            Toast.makeText(this, "Error:\n" + ex.getMessage().toString(), Toast.LENGTH_LONG).show();
            return;
        }
        if (startFile == null)
        {
            return;
        }
        StringBuilder text = new StringBuilder();  
        can = false;
        sel = false;
        try
        {
            file = new File(CurDir, startFile);
            reader = new BufferedReader(new FileReader(file));  
            String line;
            while ((line = reader.readLine()) != null)
            {
                text.append(line);  
                text.append('\n');  
            }
        }
        catch (Exception e)
        {
            Toast.makeText(this, "Error:\n" + e.getMessage().toString(), Toast.LENGTH_LONG).show();
        }
        TextEditor.setText(text);
        FileName.setText(startFile);
    }

谢谢Simon的链接,非常有帮助。我刚开始浏览它,这就是为什么我在没有加载文件时遇到了这个问题。

2 个答案:

答案 0 :(得分:0)

“默认情况下”无法执行此操作。只有用户可以选择(并删除或更改)操作的默认意图。否则,这将是混乱!

[编辑]

Lars Vogel总是很好读。试试这个教程。这很简单(几乎;)

http://www.vogella.com/articles/AndroidIntent/article.html

答案 1 :(得分:0)

您需要为处理文本文件的任何活动添加intent过滤器。安装应用程序时,过滤器已在操作系统中注册。当用户尝试启动文件时,Android会询问您要处理请求的注册应用程序。