How to share an audio from the internal raw directory?

0

I have several audios stored in the raw directory of the app and I would like to share it with other applications, like whatsapp for example, but I found the documentation on configuring the File provider very confusing.

AndroidManifest.xml

 <provider
        android:name="android.support.v4.content.FileProvider"
        android:grantUriPermissions="true"
        android:exported="false"
        android:authorities="com.namepackage.fileprovider">

        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths"/>

    </provider>

Here comes the configuration of the filepaths that I have doubt how to solve, it looks like this: filepaths.xml

 <paths>
<files-path name="files" path="/" />

    

And the Intent itself:

  File imagePath = new File(context.getFilesDir(), "nomearquivo.mp3");
        Uri uri = FileProvider.getUriForFile(context,"com.namepackege.fileprovider",
                imagePath);
        Intent share = new Intent(Intent.ACTION_SEND);
        share.putExtra(Intent.EXTRA_STREAM, uri);
        share.setType("audio/mp3");
        share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        share.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(share);

But this code does not work, I would like to change it in order to work

    
asked by anonymous 27.05.2017 / 17:53

1 answer

0

One way, in addition to others , to do this is to save the file first to the device before sending. Here's a simple method:

public Uri shareItemRaw(int songInRawId, String songOutFile) {
    File dest = Environment.getExternalStorageDirectory();
    InputStream in = getResources().openRawResource(songInRawId);

    try {
        OutputStream out = new FileOutputStream(new File(dest, songOutFile));
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf, 0, buf.length)) != -1) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    } catch (Exception ignored) {
    }

    return Uri.parse(
        Environment.getExternalStorageDirectory().toString() + "/" + songOutFile);
}

So you create your intent this way:

Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, shareItemRaw(R.raw.song, "song.mp3")); 
share.setType("audio/*");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(share);
    
27.05.2017 / 18:08