如何共享音频文件
How to share audio files
我的应用有一个 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 本质上成为您的 file/resource 的定位器,其他应用程序可以使用它来读取它。
我的应用有一个 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 本质上成为您的 file/resource 的定位器,其他应用程序可以使用它来读取它。