Android 7牛轧糖,如何从传入意图的uri获取文件路径



FileProvider:- 设置文件共享

我知道在安卓牛轧糖中更改文件策略。文件共享到其他应用的所需应用由文件提供程序生成 URI。uri 格式为 content://com.example.myapp.fileprovider/myimages/default_image.jpg

我想知道如何从 FileProvider.getUriForFile() 生成的 uri 中获取文件路径。因为"我的应用程序"需要知道物理文件路径才能保存、加载、读取信息等。可能吗

[简言]

  1. 我的应用在 andorid 7 牛轧糖上收到了其他应用的意图 uri。
  2. uri 格式为 content://com.example.myapp.fileprovider/myimages/default_image.jpg
  3. 也许它是由FileProvider.getUriForFile生成的.
  4. 我想知道从 uri 获取文件路径的方法。
  5. 我可以从getContentResolver().openFileDescriptor()获取 mime 类型、显示名称、文件大小和读取 binay。但我想知道文件路径。

您无法获取 Uri 的"文件路径",原因很简单,不需要 Uri 指向文件。使用 ContentResolver 和 openInputStream(( 等方法访问 Uri 表示的内容。

若要使用内容 URI 与其他应用共享文件,你的应用必须 生成内容 URI。若要生成内容 URI,请创建一个新的 文件,然后将文件传递给 getUriForFile((。您可以发送 getUriForFile(( 返回给另一个应用的内容 URI 意图。接收内容 URI 的客户端应用可以打开文件 并通过调用 ContentResolver.openFileDescriptor 访问其内容 以获取包裹文件描述符。 来源:安卓开发者

// Use Below Method Working fine for Android N.
private static String getFilePathForN(Uri uri, Context context) {
    Uri returnUri = uri;
    Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
    /*
     * Get the column indexes of the data in the Cursor,
     *     * move to the first row in the Cursor, get the data,
     *     * and display it.
     * */
    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
    returnCursor.moveToFirst();
    String name = (returnCursor.getString(nameIndex));
    String size = (Long.toString(returnCursor.getLong(sizeIndex)));
    File file = new File(context.getFilesDir(), name);
    try {
        InputStream inputStream = context.getContentResolver().openInputStream(uri);
        FileOutputStream outputStream = new FileOutputStream(file);
        int read = 0;
        int maxBufferSize = 1 * 1024 * 1024;
        int bytesAvailable = inputStream.available();
        //int bufferSize = 1024;
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);
        final byte[] buffers = new byte[bufferSize];
        while ((read = inputStream.read(buffers)) != -1) {
            outputStream.write(buffers, 0, read);
        }
        Log.e("File Size", "Size " + file.length());
        inputStream.close();
        outputStream.close();
        Log.e("File Path", "Path " + file.getPath());
    } catch (Exception e) {
        Log.e("Exception", e.getMessage());
    }
    return file.getPath();
}

我在我们的应用程序中有类似的要求,但之前感到困惑。我用这种方式解决了。

在 Android N 中,仅更改向第三方应用公开的文件 uri。(不是我们以前使用它的方式(。

在我们的应用程序中,我们将 uri 发送到相机应用,在该位置,我们希望相机应用存储捕获的图像。

  1. 对于 android N,我们生成新的基于 Content://uri 的 url,指向文件。
  2. 我们为相同的路径生成通常的基于文件 api 的路径(使用旧方法(。

现在我们对同一个文件有 2 个不同的 uri。 #1 与相机应用程序共享。如果相机意图是成功的,我们可以从#2访问图像。

希望这有帮助。

最新更新