我试图通过这样做来共享缓存文件夹中的 .mp3 文件:
InputStream inputStream = getContentResolver().openInputStream(UriUtils.getResourceUri(audioToShare.getAudioPath(),this));
File fileToShare = FileUtils.writeStreamToFile(this,audioToShare.getLabel(),inputStream);
Intent intent = new Intent(Intent.ACTION_SEND).setType("audio/mpeg");
intent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(fileToShare));
startActivity(Intent.createChooser(intent, "Share to"));
但是当我选择一个联系人时,让我们说whatsapp,应用程序抛出了警告。
W/Bundle: Key android.intent.extra.STREAM expected Parcelable but value was a java.io.File. The default value <null> was returned.
12-25 16:10:32.802 17021-17021/com.example.soundboard W/Bundle: Attempt to cast generated internal exception:
java.lang.ClassCastException: java.io.File cannot be cast to android.os.Parcelable
at android.os.Bundle.getParcelable(Bundle.java:894)
at android.content.Intent.getParcelableExtra(Intent.java:7075)
at android.content.Intent.migrateExtraStreamToClipData(Intent.java:9887)
at android.content.Intent.migrateExtraStreamToClipData(Intent.java:9867)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1608)
at android.app.Activity.startActivityForResult(Activity.java:4472)
at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
at android.app.Activity.startActivityForResult(Activity.java:4430)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
at android.app.Activity.startActivity(Activity.java:4791)
at android.app.Activity.startActivity(Activity.java:4759)
at com.quartzodev.cirosoundboard.sound.SoundActivity.onActionItemClicked(SoundActivity.java:170)
方法 writeStreamToFile ,以便您可以看到我如何创建缓存文件
public static File writeStreamToFile(Context context, String fileName, InputStream input){
try {
File file = new File(context.getFilesDir(), fileName);
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
return file;
} finally {
output.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
我做错了什么?
答案 0 :(得分:0)
原来我没有权限在 getFilesDir()
中共享文件夹中的文件刚刚更改为 getExternalCacheDir(),现在我可以通过Whatsapp和Gmail分享