Search code examples
androidsharefilepathintentfilter

Getting Video path from third party app (e.g. WhatsApp) to my app via content:// URI


I am trying to get video path from third party app (e.g WhatsApp) to my app (being tested on Marshmallow). When I share the video from WhatsApp and share it with my app, I get URI something like this:

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);
        }

}

How to get the path of video file from the above URI ?


Solution

  • 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
        }
    

    }

    In handleReceivedVideo() you need to open inputStream and then copy it into a file.

    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() gets you the bytes which you can upload on your server.

    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;
    

    }