如何在android中的res / raw文件夹中获取我的.mp3文件的URI

时间:2015-03-08 16:34:44

标签: android audio android-intent

我有问题。我想将我的MP3文件分享给Whatsapp,但它不起作用!这是我的分享意图:

    public void shareAchieve() {
        Intent shareAchievement = new Intent();
        shareAchievement.setType("audio/*");
        shareAchievement.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://de.logtainment.ungesoundboard/" + R.raw.achieve + ".mp3"));
        startActivity(Intent.createChooser(shareAchievement, "Teile Längstes Achievement"));
    }

但它不起作用!抱歉,我的英语不好,来自德国。

2 个答案:

答案 0 :(得分:1)

正如@CommonsWare所说 很少有应用程序支持android:resource计划 使您的应用与所有应用兼容。

您必须通过此方法将原始资源复制到内部存储

private String CopyRAWtoSDCard(int raw_id,String sharePath) throws IOException {
        InputStream in = getResources().openRawResource(raw_id);
        FileOutputStream out = new FileOutputStream(sharePath);
        byte[] buff = new byte[1024];
        int read = 0;
        try {
            while ((read = in.read(buff)) > 0) {
                out.write(buff, 0, read);
            }
        } finally {
            in.close();
            out.close();
        }
        return sharePath;
    }

用以下代码替换您的方法

  public void shareAchieve() {
    Intent shareAchievement = new Intent(Intent.ACTION_SEND);
    shareAchievement.setType("audio/*");

    String sPath= null;
    try {
        sPath = CopyRAWtoSDCard(R.raw.filename, Environment.getExternalStorageDirectory()+"/filename.mp3");
    } catch (IOException e) {
        e.printStackTrace();
    }
    Uri uri = Uri.parse(sPath);

    shareAchievement.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    shareAchievement.putExtra(Intent.EXTRA_STREAM,uri);
    startActivity(Intent.createChooser(shareAchievement, "Teile Längstes Achievement"));
}

同时添加

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

答案 1 :(得分:0)

您错过了添加/ raw /到路径并更改您的意图

更改

Intent shareAchievement= new Intent();
shareAchievement.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://de.logtainment.ungesoundboard/" + R.raw.achieve + ".mp3"));

Intent shareAchievement= new Intent(Intent.ACTION_SEND);
shareAchievement.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://de.logtainment.ungesoundboard/raw/achieve.mp3"));