Android Q生成file适配问题
chenchi0920 opened this issue · comments
chenchi0920 commented
public static Bitmap shouldKeepSampling(Uri uri, final Tiny.FileCompressOptions options) throws Exception {
if (uri == null)
return null;
final Bitmap[] result = {null};
if (UriUtil.isNetworkUri(uri)) {
HttpUrlConnectionFetcher.fetch(uri, new HttpUrlConnectionFetcher.ResponseCallback() {
@Override
public void callback(InputStream is) {
byte[] decodeBytes = CompressKit.transformToByteArray(is);
if (options.isKeepSampling) {
BitmapFactory.Options decodeOptions = CompressKit.getDefaultDecodeOptions();
decodeOptions.inPreferredConfig = options.config;
result[0] = BitmapFactory.decodeByteArray(decodeBytes, 0, decodeBytes.length, decodeOptions);
} else {
result[0] = BitmapCompressor.compress(decodeBytes, options, true);
}
}
});
} else if (UriUtil.isLocalContentUri(uri) || UriUtil.isLocalFileUri(uri)) {
String filePath = UriUtil.getRealPathFromUri(uri);
if (TextUtils.isEmpty(filePath))
return null;
if (Conditions.fileIsExist(filePath) && Conditions.fileCanRead(filePath)) {
FileInputStream fis = null;
File file = new File(filePath);
try {
fis = new FileInputStream(file);
byte[] decodeBytes = CompressKit.transformToByteArray(fis);
if (options.isKeepSampling) {
BitmapFactory.Options decodeOptions = CompressKit.getDefaultDecodeOptions();
decodeOptions.inPreferredConfig = options.config;
result[0] = BitmapFactory.decodeByteArray(decodeBytes, 0, decodeBytes.length, decodeOptions);
} else {
result[0] = BitmapCompressor.compress(decodeBytes, options, true);
}
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
//ignore...
}
}
}
}
return result[0];
}
在Android Q上直接new File()在去判断是否存在会失败
chenchi0920 commented
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ParcelFileDescriptor pfd = null;
try {
pfd = Tiny.getInstance().getApplication().getContentResolver().openFileDescriptor(uri, "r");
if (pfd != null) {
fis = new FileInputStream(pfd.getFileDescriptor());
byte[] decodeBytes = CompressKit.transformToByteArray(fis);
if (options.isKeepSampling) {
BitmapFactory.Options decodeOptions = CompressKit.getDefaultDecodeOptions();
decodeOptions.inPreferredConfig = options.config;
result[0] = BitmapFactory.decodeByteArray(decodeBytes, 0, decodeBytes.length, decodeOptions);
} else {
result[0] = BitmapCompressor.compress(decodeBytes, options, true);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (pfd != null) {
pfd.close();
}
if (fis != null)
fis.close();
}
}
适配完的读取文件