我使用这种方法从uri获取文件,在所有设备上都可以正常工作,但只能在三星设备上崩溃!
fun Activity.getFilePath(uri: Uri): File {
var cursor: Cursor? = null
return try {
val dataArray = arrayOf(MediaStore.Images.Media.DATA)
cursor = contentResolver.query(uri, dataArray, null, null, null)
val index = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor?.moveToFirst()
File(index?.let { cursor?.getString(it) })
} catch (e: Exception) {
throw KotlinNullPointerException("File not founded")
} finally {
cursor?.close()
}
}
从图库中获取图片
fun Activity.chooseImageFromGallery(withAskPermission: Boolean) {
if (isPermissionsGranted(Manifest.permission.READ_EXTERNAL_STORAGE)) {
val intent = Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST)
} else {
if (withAskPermission && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
PICK_IMAGE_REQUEST)
}
}
}
关于活动结果
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && requestCode == PICK_IMAGE_REQUEST) {
uri = data?.data
file = uri?.let { activity?.getFilePath(it) }
//
}
}