调用File.createNewFile()时,权限被拒绝 Android的

我试图创建一个图像文件到外部存储来分享它。 但在尝试下面的代码时,我有一些错误

var icon: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.namelogo) val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = "image/*" val bytes = ByteArrayOutputStream() icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes) val path = File.separator + "temporary_file.jpg" val f = File(Environment.getExternalStorageDirectory().toString(), path) try { if (!f.parentFile.exists()) f.parentFile.mkdirs() if (!f.exists()) f.createNewFile() f.createNewFile() val fo = FileOutputStream(f) fo.write(bytes.toByteArray()) } catch (e: IOException) { Log.e("path = ", "+ $path " + e.toString()) e.printStackTrace() } shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/IronyBalls/temporary_file.jpg")); startActivity(Intent.createChooser(shareIntent, "Share Image")) 

直到现在我找到解决方案只使用

 if (!f.parentFile.exists()) f.parentFile.mkdirs() if (!f.exists()) f.createNewFile() 

设置权限

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

我已经使用过了。但是在错误标签中仍然出现下面的错误

E / path =:+ /temporary_file.jpg java.io.IOException:权限被拒绝

并在信息标签

W / System.err:java.io.IOException:权限被拒绝

W / System.err:在java.io.UnixFileSystem.createFileExclusively0(本地方法)

W / System.err:在java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)

W / System.err:在java.io.File.createNewFile(File.java:948)W / System.err:at com.irony.balls.MainActivity $ onCreate $ 8.onClick(MainActivity.kt:277)

W / System.err:在android.view.View.performClick(View.java:5611)

10-15 20:33:17.912 29759-29759 / com.irony.balls W / System.err:在android.view.View $ PerformClick.run(View.java:22276)10-15 20:33:17.912 29759- 29759 / com.irony.balls W / System.err:at android.os.Handler.handleCallback(Handler.java:751)10-15 20:33:17.912 29759-29759 / com.irony.balls W / System.err :at android.os.Handler.dispatchMessage(Handler.java:95)10-15 20:33:17.912 29759-29759 / com.irony.balls W / System.err:at android.os.Looper.loop(Looper。 java:154)10-15 20:33:17.912 29759-29759 / com.irony.balls W / System.err:at android.app.ActivityThread.main(ActivityThread.java:6195)10-15 20:33:17.912 29759-29759 / com.irony.balls W / System.err:在java.lang.reflect.Method.invoke(Native Method)10-15 20:33:17.912 29759-29759 / com.irony.balls W / System。 err:在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:874)

10-15 20:33:17.912 29759-29759 / com.irony.balls W / System.err:at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:764)

如果您的设备在Android 6或更高版本上工作,您是否已经请求了运行时权限?

有关更多详细信息,请参阅https://developer.android.com/training/permissions/requesting.html