1. 程式人生 > >Android 7.0以上系統獲取以content開頭的檔案拿不到正確路徑,報錯column-data-does-not-exist

Android 7.0以上系統獲取以content開頭的檔案拿不到正確路徑,報錯column-data-does-not-exist

我們專案的使用場景,手機qq開啟檔案,選擇其他開啟方式,選擇我們自己的應用開啟,通過intent.getData()獲取檔案地址,後來發現在Android7.0之後的版本,獲取到的地址不正確,說檔案不存在。日誌報錯column-data-does-not-exist,

經過一天的折騰,終於在網上找到了一些零碎的知識拼接成了解決辦法,具體如下:

判斷版本獲取路徑的方式,在拿到uri之後進行版本判斷大於等於24(即Android7.0)用最新的獲取路徑方式,否則用你之前的方式,

String str ="";
if (Build.VERSION.SDK_INT >= 24) {
    str = getFilePathFromURI(this, uri);//新的方式
} else {
    //str = getPath(this, uri);你自己之前的獲取方法
}
public String getFilePathFromURI(Context context, Uri contentUri) {
    File rootDataDir = context.getFilesDir();
    String fileName = getFileName(contentUri);
    if (!TextUtils.isEmpty(fileName)) {
        File copyFile = new File(rootDataDir + File.separator + fileName);
        copyFile(context, contentUri, copyFile);
        return copyFile.getAbsolutePath();
    }
    return null;
}

public static String getFileName(Uri uri) {
    if (uri == null) return null;
    String fileName = null;
    String path = uri.getPath();
    int cut = path.lastIndexOf('/');
    if (cut != -1) {
        fileName = path.substring(cut + 1);
    }
    return fileName;
}

public void copyFile(Context context, Uri srcUri, File dstFile) {
    try {
        InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
        if (inputStream == null) return;
        OutputStream outputStream = new FileOutputStream(dstFile);
        copyStream(inputStream, outputStream);
        inputStream.close();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public int copyStream(InputStream input, OutputStream output) throws Exception, IOException {
    final int BUFFER_SIZE = 1024 * 2;
    byte[] buffer = new byte[BUFFER_SIZE];
    BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
    BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
    int count = 0, n = 0;
    try {
        while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
            out.write(buffer, 0, n);
            count += n;
        }
        out.flush();
    } finally {
        try {
            out.close();
        } catch (IOException e) {
        }
        try {
            in.close();
        } catch (IOException e) {
        }
    }
    return count;
}

希望能解決你們遇到的問題。