Error: Cannot attach empty file in GMAIL app using File provider

自闭症网瘾萝莉.ら 提交于 2019-11-30 14:44:49

问题


I am trying to attach a pdf file in gmail app. I have read this and this (applied solution) I am trying as;

public static void attachFile(Context ctx) {
    String TAG = "Attach";
    File documentsPath = new File(ctx.getFilesDir(), "documents");
    Log.i(TAG,"documentsAbsolutePath Output");
    Log.i(TAG, documentsPath.getAbsolutePath().toString());
    File file = new File(documentsPath, "sample.pdf");
    if ( file.exists() ) {
        Toast.makeText(ctx, "Exits", Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(ctx, "Not Exist", Toast.LENGTH_LONG).show();
    }
    Log.i(TAG,"file Output");
    Log.i(TAG, file.toString());
    Log.i(TAG, String.valueOf(file.length()));
    Uri uri = FileProvider.getUriForFile(ctx, "com.example.fyp_awais.attachfiletest2.fileprovider", file);
    Log.i(TAG,"URI Output");
    Log.i(TAG,uri.toString());
    Intent intent = ShareCompat.IntentBuilder.from((Activity) ctx)
            .setType("application/pdf")
            .setStream(uri)
            .setChooserTitle("Choose bar")
            .createChooserIntent()
            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    ctx.startActivity(intent);
}

Outputs

documentsAbsolutePath Output
/data/data/com.example.fyp_awais.attachfiletest2/files/documents
 file Output
/data/data/com.example.fyp_awais.attachfiletest2/files/documents/sample.pdf
 0
 URI Output
 content://com.example.fyp_awais.attachfiletest2.fileprovider/pdf_folder/sample.pdf

Menifest

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.example.fyp_awais.attachfiletest2.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/filepath" />
</provider>

FilePath.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
        <files-path name="pdf_folder" path="documents/"/>
    </paths>
</PreferenceScreen

A pdf file is saved in Galaxy Core Prime\Phone\documents. (file size: 53.7KB)

But it gives

Cannot attach empty file.

I am confused with folder-name in this line <files-path name="pdf_folder" path="documents/"/>. The file is in the \Phone\documents. Then why folder name?

Edit 1

Tried to replace setType(application/pdf) with setType("message/rfc822") But did not work. Any help?


回答1:


Send the file in URI format like this:

Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
        emailIntent.setData(Uri.parse("mailto:"));
        emailIntent.setType("application/image");
        emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
        emailIntent.putExtra(Intent.EXTRA_CC, CC);
ArrayList<Uri> uris = new ArrayList<>();
        //convert from paths to Android friendly Parcelable Uri's
        uris.add(frontImageUri);
        uris.add(backImageUri);
        emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivity(Intent.createChooser(emailIntent, "Send mail..."));



回答2:


if it's ok To send Zip then try this way

String fileNameStor_zip = Environment.getExternalStorageDirectory() + "/" + fileName + ".zip";

String[] path = { your 1st pdf File Path, your 2nd pdf File Path};

Compress compress = new Compress(path, fileNameStor_zip);

compress.zip();

URI = Uri.parse("file://" + fileNameStor_zip);

Provide your Gmail Intent

intent.putExtra(Intent.EXTRA_STREAM, URI);




回答3:


Uri contentUri = FileProvider.getUriForFile(this, "com.mydomain.fileprovider", newFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
i.setData(contentUri);



回答4:


String filename="my_file.vcf"; 
File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
Uri path = Uri.fromFile(filelocation); 
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// set the type to 'email'
emailIntent .setType("vnd.android.cursor.dir/email");
String to[] = {"asd@gmail.com"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
emailIntent .putExtra(Intent.EXTRA_STREAM, path);
// the mail subject
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(emailIntent , "Send email..."));



回答5:


You have to grant the permission to access storage for gmail.




回答6:


In case it helps- here's what I do in an app debug function with a few files, it shouldn't really be any different. I do copy/export them into a user-public folder first before attaching them, and make them world readable.

 if (verifyStoragePermissions(c)) {
        final Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"recipient@email.address"});
        intent.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");

        //build up message
        ArrayList<Uri> uris = new ArrayList<>();
        StringBuilder content = new StringBuilder();
        content.append(
                String.format(
                        c.getString(R.string.message_log_upload_email_body) +
                                "\n\nmodelDesc:%s \n\nmanuf:%s \n\naId: %s,\n\nhIid: %s,\n\nfbId: %s.",
                        Build.MODEL, Build.MANUFACTURER, getSomeVar1(), getSomeVar2(), getSomeVar3())
        );
        content.append("\n\nMy logged in account id is: ").append(getAccountId(c)).append(".");
        content.append("\n\nHere's an overview of my attachments:\n");

        for (String s : addresses) {
            File f = new File(s);
            //noinspection ResultOfMethodCallIgnored
            f.setReadable(true, false);
            Uri add = Uri.fromFile(f);
            //add attachment manifest
            content.append(String.format(Locale.UK, "|->  %s (%.3f kb)\n", f.getName(), (float) f.length() / 1024));
            uris.add(add);
        }
        //attach the things
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        //set content/message
        intent.putExtra(Intent.EXTRA_TEXT, content.toString());
        c.startActivity(intent);
    }
}

addresses is a String[] param to that function. I build it up by making the functions I use to export the files return arrays of strings of the addresses of the files they've exported - as I initially store the files in my app's private storage



来源:https://stackoverflow.com/questions/43316201/error-cannot-attach-empty-file-in-gmail-app-using-file-provider

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!