Android从Gmail应用获取附件文件名

3
我需要从Gmail应用中检索出内容的文件名。
我会得到类似以下的内容URI:

content://gmail-ls/messages/mymailid%40gmail.com/4/attachments/0.1/BEST/false

我看到一些应用程序从中获取文件名,例如this app
请帮忙解决此问题。
提前致谢。
2个回答

11

基本上,您需要获取文件系统并获得存储信息的光标:

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Toast;

public class CheckIt extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent theIntent = getIntent();
        String attachmentFileName = "No file name found";
        if (theIntent != null && theIntent.getData() != null) {
            Cursor c = getContentResolver().query(
                theIntent.getData(), null, null, null, null);
            c.moveToFirst();
            final int fileNameColumnId = c.getColumnIndex(
                MediaStore.MediaColumns.DISPLAY_NAME);
            if (fileNameColumnId >= 0)
                attachmentFileName = c.getString(fileNameColumnId);
        }
        Toast.makeText(this, attachmentFileName, Toast.LENGTH_LONG).show();
    }

}

在返回的光标中还有另一列 - MediaStore.MediaColumns.SIZE。至少这是我在Desire HD上使用GMail获取到的。只需在 GMail 中打开邮件并点击预览按钮即可尝试上述代码。

当然,不要忘记将以下内容添加到Manifest.xml中的activity部分(不要删除android.intent.category.LAUNCHER intent-filter部分,否则它将无法通过启动器查看):

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="*/*" /> 
</intent-filter>

我很感激你的努力,但我的意图不是空的,而是游标C为空。 - Jana
嗯,这很奇怪。当我在GMail中点击预览按钮并选择CkeckIt时,在我的手机上显示了文件名。你能提供监听意图的活动代码吗? - Kamen
@Kamen,你是如何获取文件数据的呢?我看到了文件名和大小,但这些数据的路径在哪里呢? - Jona
2
请查看此处:http://carvingcode.blogspot.com/2009/08/how-to-open-gmail-attachments-with.html - Kamen
6
这段代码存在两个问题:使用完cursor后需要close()它,而且应该通过将new String[]{MediaStore.MediaColumns.DISPLAY_NAME}作为ContentResolver.query()的第二个参数(即projection)来仅请求所需的列。 - Adam Rosenfield

0
你需要做的是注册不同的MIME类型。就像这样:
<intent-filter>
<action name="android.intent.action.VIEW">
<category name="android.intent.category.DEFAULT">
<data mimetype="text/xml">
</intent-filter>

然后,当尝试从 Gmail 打开附件时,Android 将列出您的应用程序作为选项。然后它将使用意图启动您的应用程序,该意图会提供 uri。


我已经在我的应用程序中打开了文件内容,但是我无法从Gmail中检索文件名。 - Jana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接