通过 content:// URI获取从第三方应用程序(例如WhatsApp)到我的应用程序的视频路径



我正在尝试获取从第三方应用程序(例如WhatsApp(到我的应用程序(在棉花糖上测试(的视频路径。当我从WhatsApp共享视频并将其与我的应用程序共享时,我得到的URI如下所示:

content://com.whatsapp.provider.media/item/12

// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
} else if (type.startsWith("image/")) {
} else if (type.startsWith("video/")) {
Uri videoUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
}

}

如何从上面的URI中获取视频文件的路径?

if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
} else if (type.startsWith("image/")) {
} else if (type.startsWith("video/")) {
handleReceivedVideo(intent); // Handle video received from whatsapp URI
}

}

handleReceivedVideo((中,你需要打开inputStream,然后将其复制到文件中。

void handleReceivedVideo(Intent intent) throws IOException {
Uri videoUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (videoUri != null) {
File file = new File(getCacheDir(), "video.mp4");
InputStream inputStream=getContentResolver().openInputStream(videoUri);
try {
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
}
} finally {
inputStream.close();
byte[] bytes =getFileFromPath(file);
}
}

}

getFileFromPath((获取可以上传到服务器上的字节数。

public static byte[] getFileFromPath(File file) {
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bytes;

}

相关内容

最新更新