碰巧,我遇到了几乎相同的问题:我需要共享视频文件。问题是:现在有办法共享内部文件。绝不。
你要么需要一个ContentProvider
,或者因为它更简单一些,所以它是扩展FileProvider
.
第一:你需要更新你的信息AndroidManifest.xml
:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="my.package.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
这需要添加到<application>
tag.
然后你需要 XML 文件file_paths.xml
在Android子目录中res/xml/
它应该是这样的:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="objects" path="objects/"/>
</paths>
为了最终触发它,我需要这样调用它:
Uri uri = Uri.parse("content://my.package.fileprovider/" + fn);
Intent intent = new Intent(Intent.ACTION_VIEW, uri); // or parse uri each time
intent.setDataAndType(uri, "video/*"); // all video type == * - alternative: mp4, ...
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_GRANT_READ_URI_PERMISSION);
List<ResolveInfo> resInfoList = FXActivity.getInstance().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
FXActivity.getInstance().grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
FXActivity.getInstance().startActivity(intent);
但是在能够像这样使用它之前我需要做的是:我需要将所有资产复制到私有文件目录,因为FileProvider
本身没有访问您的资产的选项(我想您可以通过自定义来实现这一点ContentProvider
,但我发现方法很复杂并且没有那么多时间)。
See 有关 FileProvider 的 Android 开发人员参考了解更多信息。
我的简单解决方案如下所示:
public boolean copyAssetsToStorage() throws NativeServiceException {
try {
String[] assets = getContext().getAssets().list(DIR_NAME);
if (assets == null || assets.length == 0) {
LOG.warning("No assets found in '" + DIR_NAME + "'!");
return false;
}
File filesDir = getContext().getFilesDir();
File targetDir = new File(filesDir, DIR_NAME);
if (!targetDir.isDirectory()) {
boolean b = targetDir.mkdir();
if (!b) {
LOG.warning("could not create private directory with the name '" + DIR_NAME + "'!");
return false;
}
}
for (String asset : assets) {
File targetFile = new File(targetDir, asset);
if (targetFile.isFile()) {
LOG.info("Asset " + asset + " already present. Nothing to do.");
continue;
} else {
LOG.info("Copying asset " + asset + " to private files.");
}
InputStream is = null;
OutputStream os = null;
try {
is = getContext().getAssets().open(DIR_NAME + "/" + asset);
os = new FileOutputStream(targetFile.getAbsolutePath());
byte[] buff = new byte[1024];
int len;
while ((len = is.read(buff)) > 0)
os.write(buff, 0, len);
} catch (IOException e) {
LOG.log(Level.SEVERE, e.getMessage(), e);
continue;
}
if (os != null) {
os.flush();
os.close();
}
if (is != null)
is.close();
}
return true;
} catch (IOException e) {
LOG.log(Level.SEVERE, e.getMessage(), e);
return false;
}
}
正如你所看到的,我现在只支持平面层次结构......
这至少对我有用。
问候,
丹尼尔
附加问题:为什么要发送 Intent 而不实现简单的 JavaFX 音频播放器控件?这是我在制作视频之前所做的。