Android接收共享文本文件但不共享文本内容

时间:2012-03-02 10:22:36

标签: android text share intentfilter extra

我正在创建一个能够上传单个或多个文件或文件夹的应用。 intent-filter的定义如下:

    <activity android:name=".UploadActivity" android:launchMode="singleTop" android:theme="@style/Theme.Sherlock">
        <intent-filter android:label="@string/upload_intent">
            <action android:name="android.intent.action.SEND" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:mimeType="application/*" />
            <data android:mimeType="audio/*" />
            <data android:mimeType="image/*" />
            <data android:mimeType="media/*" />
            <data android:mimeType="multipart/*" />
            <data android:mimeType="text/*" />
            <data android:mimeType="video/*" />
        </intent-filter>
        <intent-filter android:label="@string/upload_intent">
            <action android:name="android.intent.action.SEND_MULTIPLE" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:mimeType="*/*" />
        </intent-filter>
    </activity>

这适用于Blackmoon文件资源管理器和Android 4.0.3图库。我的应用程序显示在“共享”菜单中。但是,它也会在浏览器中显示,当您长按URL并选择共享页面时。

当我发送文本文件到我的应用程序时,我明白了:

getIntent().getAction() returns Intent.ACTION_SEND
getIntent().getType() returns "text/plain"
getIntent().getScheme() returns null
getIntent().getExtras().getString(Intent.EXTRA_STREAM) returns the filename

但是,从浏览器发送URL会返回相同的内容减去 Intent.EXTRA_STREAM。我可以在代码中轻松地检测到这一点并说“嘿,我无法上传文字!”#34;但我宁愿改变意图过滤器,以便只有在有EXTRA_STREAM时触发它。是否可以这样做?

(我尝试使用android:scheme但是它不会区分文件和共享的文本字符串,因为它们都是空的......)

2 个答案:

答案 0 :(得分:3)

你有:

getIntent().getExtras().getString(Intent.EXTRA_STREAM) returns the filename

AFAIK,Android从不向您发送打开fh或套接字到文件。只是文件的简单旧路径,然后处理:

File somefile = new File(filename);

然后阅读或写入或不写。

对于传入的文本是EXTRA_TEXT或STREAM,只需测试两者并适当处理。希望这会有所帮助。

答案 1 :(得分:0)

我在清单中注册了file

<activity android:name=".ReaderActivity">
    <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>

然后在我的活动中使用getData()和一个内容解析器。

Uri uri = getIntent().getData();
InputStream inputStream = getContentResolver().openInputStream(uri);
...

请参阅this answer找出...是什么。