我的应用程序的ListView
包含多个音频文件。如果用户长按ListViewItem
,它将共享所选的音频文件。
我已经读过,为了共享内容,首先我必须将文件复制到外部存储中,然后再共享。
我使用以下代码来做到这一点:
private void copyToExternalStorage(String sourceFilePath, String fileName)
{
File sourceFile = new File(sourceFilePath);
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myApp";
File destinationFile = new File(destinationPath);
if (!destinationFile.exists())
destinationFile.mkdirs();
destinationFile = new File(destinationPath + "/" + fileName + ".mp3");
try
{
FileUtils.copyFile(sourceFile, destinationFile);
} catch (IOException e)
{
e.printStackTrace();
}
}
private void share(String file, String trackName)
{
copyToExternalStorage(file, trackName);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("audio/*");
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myApp/" +
trackName +
".mp3";
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
startActivity(Intent.createChooser(shareIntent, "Share audio"));
}
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l)
{
share(getResources().getStringArray(R.array.sounds)[i], getResources().getStringArray(R.array.tracks)
[i]);
return true;
}
R.array.sounds
是我存储音频文件的位置,R.array.tracks
是我存储音轨名称的位置。我遇到的问题是我的应用程序在给定的
sourceFilePath
中找不到任何文件,因此它不会复制或共享任何内容。任何帮助都感激不尽。
最佳答案
您不必在任何地方复制文件。让您的应用公开响应您共享的Uri的ContentProvider会更安全,更安全(但工作更多)。 Uri本质上成为文件/资源的定位器,其他应用程序可以使用它来读取它。
查看official docs on file sharing入门。
关于android - 如何共享音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35387000/