Android - get email attachment name in my application

来源:互联网 发布:剑网3毒哥捏脸数据 编辑:程序博客网 时间:2024/05/19 05:31

之前从邮箱里面打开文件会调用我们的程序,然后我们的程序将文件通过流的方式读到本地,但是之前在传过来的intent里面没有文件名字的信息,所以一直用“附件”作为文件的名字,这样一是不能正确显示邮件里面文件的真实名字,再就是出现了其他的问题,看到其他的程序却可以显示,刚开始以为是通过底层解析获得的,但发现不是,原来还是通过android的机制就可以获得

还有特写要强调一点的就是,之前在网上搜这个问题的时候都是用的中文搜索的,都没有搜索到解决的办法,今天用英文一搜就搜索出来了,看来以后要习惯用英文搜索。

http://stackoverflow.com/questions/6035535/android-get-email-attachment-name-in-my-application

'm trying to load an email attachment in my application. I can get the content, but I cannot get the file name.

Here's how my intent filter looks like:

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

Here is what I get:

INFO/ActivityManager(97): Starting: Intent { act=android.intent.action.VIEW dat=content://gmail-ls/messages/john.doe%40gmail.com/42/attachments/0.1/SIMPLE/false typ=image/jpeg flg=0x3880001 cmp=com.myapp/.ui.email.EmailDocumentActivityJpeg } from pid 97

In my activity I get the Uri and use it to get the input stream for the file content:

InputStream is = context.getContentResolver().openInputStream(uri);

Where can I find the file name in this scenario?


I had the same problem to solve today and ended up finding the solution in another post : Android get attached filename from gmail app The main idea is that the URI you get can be used both for retrieving the file content and for querying to get more info. I made a quick utility function to retrieve the name :

public static String getContentName(ContentResolver resolver, Uri uri){    Cursor cursor = resolver.query(uri, null, null, null, null);    cursor.moveToFirst();    int nameIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);    if (nameIndex >= 0) {        return cursor.getString(nameIndex);    } else {        return null;    }}

You can use it this way in your activity :

Uri uri = getIntent().getData();String name = getContentName(getContentResolver(), uri);

That worked for me (retrieving the name of PDF files).


Shit 按照上面的步骤来,在我的HTC的手机上是好的,可是跑到联想和魅族的手机上就出问题那个nameIndex返回的是-1,折腾了一下午终于解决了,其实很简单:

public static String getEmailFileName(ContentResolver resolver, Uri uri){    Cursor cursor = resolver.query(uri, new String[]{"_display_name"}, null, null, null);    cursor.moveToFirst();    int nameIndex = cursor.getColumnIndex("_display_name");    if (nameIndex >= 0) {        return cursor.getString(nameIndex);    } else {        return null;    }}

原创粉丝点击