【问题标题】:Getting Video path from third party app (e.g. WhatsApp) to my app via content:// URI通过 content:// URI 从第三方应用程序(例如 WhatsApp)获取视频路径到我的应用程序
【发布时间】:2019-02-09 10:41:31
【问题描述】:

我正在尝试获取从第三方应用(例如 WhatsApp)到我的应用(在 Marshmallow 上进行测试)的视频路径。当我从 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 中获取视频文件的路径?

【问题讨论】:

标签: android share filepath intentfilter


【解决方案1】:
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;

}

【讨论】:

  • 伙计,我不敢相信没有文件或文章谈论这个!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多