Get real path from Uri - DATA is deprecated in android Q

后端 未结 2 1563
感情败类
感情败类 2020-12-05 08:49

I\'m successfully implementing a method for retrieving the real path of an image from gallery by the Uri returned from ACTION_PICK intent. Here\'s

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 09:26

    This question came up for me too a week ago.

    My solution was to create an InputStream from the URI and then, from this, create an OutputStream by copying the contents of the input stream.

    Note: You could call this method using an asynchronous call because copying extremely large files could have some delays and you won't want to block your UI

    @Nullable
    public static String createCopyAndReturnRealPath(
           @NonNull Context context, @NonNull Uri uri) {
        final ContentResolver contentResolver = context.getContentResolver();
        if (contentResolver == null)
            return null;
    
        // Create file path inside app's data dir
        String filePath = context.getApplicationInfo().dataDir + File.separator
                + System.currentTimeMillis();
    
        File file = new File(filePath);
        try {
            InputStream inputStream = contentResolver.openInputStream(uri);
            if (inputStream == null)
                return null;
    
            OutputStream outputStream = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0)
                outputStream.write(buf, 0, len);
    
            outputStream.close();
            inputStream.close();
        } catch (IOException ignore) {
            return null;
        }
    
        return file.getAbsolutePath();
    }
    

提交回复
热议问题