我的Android项目的原始文件夹中有各种音频文件。我的代码无法正常工作。当我单击共享按钮应用程序时,它崩溃了。
这是我的代码:
public void onClick(View v) {
InputStream inputStream;
FileOutputStream fileOutputStream;
try {
inputStream = getResources().openRawResource(R.raw.numer_1);
fileOutputStream = new FileOutputStream(
new File(Environment.getExternalStorageDirectory(), "sound.mp3"));
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
}
inputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/sound.mp3" ));
intent.setType("audio/*");
startActivity(Intent.createChooser(intent, "Share sound"));
}
Android清单添加:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
答案 0 :(得分:0)
if you use this your app will not crash again. The problem is at **Environment.getExternalStorageDirectory()**you're missing **.getPath()**
使用以下代码作为您意图的指南。
final Intent audIntent = new Intent(android.content.Intent.ACTION_SEND);
String audioName="kidi.mp3";
audIntent.setType("audio/mp3");
audIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.parse("file://"+"/Environment.getExternalStorageDirectory().getPath()/"+audioName));
startActivity(Intent.createChooser(audIntent, "Share Audio "));