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

时间:2018-09-04 11:44:55

标签: android share filepath intentfilter

我正在尝试从第三方应用程序(例如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获取视频文件的路径?

1 个答案:

答案 0 :(得分:0)

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;

}