在Android Studio中,我很难使用ShareCompat
和FileProvider
共享音频文件...我以1个音频文件为例:
/storage/emulated/0/Music/JPlayer/Cornerstone.m4a
如果我运行代码并将音频文件共享到Whatsapp,它将在Whatsapp中显示以下消息:“共享失败,请重试” 如果我运行代码并将音频文件共享给电报,它将在电报中显示以下消息:不支持的附件
这是我的代码:
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this, Array(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE), MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
final File file = new File("/storage/emulated/0/Music/JPlayer/Cornerstone.m4a");
final Uri uri = FileProvider.getUriForFile(this, this.getPackageName() + ".provider", file);
Intent intent = ShareCompat.IntentBuilder.from(this)
.setType("audio/*")
.setStream(uri)
.setChooserTitle("Choose File client")
.getIntent();
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
startActivity(intent);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
for (int i : grantResults) {
if (i == PackageManager.PERMISSION_DENIED) {
return;
}
}
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
} Manifest.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
xml / provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>