我正在尝试将图片写入手机的外部存储器(外部存储),但未创建文件夹和文件本身。在一台设备上一切正常,但在另一台设备上却没有,写入访问被拒绝。它可以在其上运行,有一个版本的 sdk 25,另一个版本是 29。
java.io.FileNotFoundException:/storage/emulated/0/1588875980977.jpg:打开失败:EACCES(权限被拒绝)
private fun checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE), 100)
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == 100) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
settings.edit().putBoolean("save", true).apply()
} else {
settings.edit().putBoolean("save", false).apply()
}
}
}
private fun getImageUriFromBitmap(bitmap: Bitmap?): Uri{
val path = Environment.getExternalStorageDirectory().toString()
val file = File(path,System.currentTimeMillis().toString() + ".jpg")
val output = FileOutputStream(file)
bitmap!!.compress(Bitmap.CompressFormat.JPEG, 100, output)
output.flush()
output.close()
return Uri.fromFile(file)
}