Android Java : How to open a downloaded file using FileProvider in another App

限于喜欢 提交于 2020-01-17 04:36:06

问题


I have the following setup, but when opening the file in third party app, the file is not being found.

After downloading a file(In bytes), I store it.

public File storeFile(byte[] b, String ref) throws IOException {
      String           path = String.valueOf(ref).replaceAll("/+", "_");
      final File       f    = new File(A.getDir(path, Context.MODE_PRIVATE), "downloads");
      FileOutputStream out  = new FileOutputStream(f);
      out.write(b);
      out.flush();
      out.close();
      return f;
   }

Then try to read it and open it.

try {
    Uri  uri               = Uri.fromFile(storeFile(bytes, ref));
    MimeTypeMap mime       = MimeTypeMap.getSingleton();
    Intent      i          = new Intent(Intent.ACTION_VIEW);
    String      type       = mime.getMimeTypeFromExtension(ext);
    File        imagePath  = new File(getFilesDir(), "downloads");
    File        file    = new File(imagePath, uri.getPath());
    Uri         newUri     = FileProvider.getUriForFile(context, "com.do.app.fileprovider", file);

    i.setDataAndType(uriContent, type);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    A.startActivity(i);
} catch (IOException e) {
    e.printStackTrace();
}

And in Manifest

<provider
     android:name="android.support.v4.content.FileProvider"
     android:authorities="com.do.app.fileprovider"
     android:exported="false"
     android:grantUriPermissions="true">
     <meta-data
          android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/provider_paths"/>
</provider>

Paths

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="cloud_files" path="downloads"/>
</paths>

I can't seem to find what I'm missing.


回答1:


File        imagePath  = File(getFilesDir(), "downloads");

That is a completely different directory as used in

 File       f    = new File(A.getDir(path, Context.MODE_PRIVATE), "downloads");

Just compare imagePath.getAbsolutePath() and f.getAbsolutePath();

You better do not construct the same path or File instance twice but use one variable instead.

UPDATE.

I now see that your code is even a bigger mess.

Uri  uri               = Uri.fromFile(storeFile(bytes, ref));
Uri         newUri     = FileProvider.getUriForFile(context, "com.do.app.fileprovider", file);

You are not using uri or newUri at all but instead contentUri. And why two/three uries? Change to one.

Uri uri  = FileProvider.getUriForFile(context
        , "com.do.app.fileprovider"
        , storeFile(bytes, ref));

And then put that uri with setDataAndType()in the used intent.



来源:https://stackoverflow.com/questions/40355076/android-java-how-to-open-a-downloaded-file-using-fileprovider-in-another-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!