我正在开发一个允许用户导入视频并对其进行编辑的应用程序。这些应用程序允许用户导入本地视频,或从 Google 相册或云端硬盘导入视频。以下代码正在运行
Intent i = new Intent();
i.setType("video/mp4");
i.setAction(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(i, REQUEST_CODE);
然后,在 onActivityResult 方法上,我从照片或云端硬盘复制到文件
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
File app_directory = new File(storage, APP_NAME);
if (!app_directory.exists())
app_directory.mkdirs();
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String filename = String.format("VID_%s.mp4", timestamp);
File file = new File(app_directory, filename);
InputStream is = getContentResolver().openInputStream(uri);
OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int read;
while ((read = is.read(buffer)) != -1)
output.write(buffer, 0, read);
output.flush();
output.close();
} catch (FileNotFoundException e) {
Toast.makeText(this, "File Not Found", Toast.LENGTH_LONG).show();
Log.e(TAG, "File Not Found", e);
} catch (IOException e) {
Toast.makeText(this, "Could not save the file", Toast.LENGTH_LONG).show();
Log.e(TAG, "IOException", e);
}
}
然而,自从谷歌照片应用程序的最新更新以来,我只得到了一个非常小的文件,我无法用任何应用程序打开,有时对于最旧的视频,我得到一个 FileNotFoundException
我尝试了几种解决方案,例如更改请求这样的文件的意图
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("video/mp4");
startActivityForResult(i, REQUEST_CODE);
或通过 FileDescriptor 获取 InputStream
ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
InputStream is = new FileInputStream(fileDescriptor);
结果相同