我试图创建一个映像文件到外部存储以分享它。但在尝试下面的代码我有一些错误调用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" />
,我有已经使用过。但仍然出现如下错误 in 错误选项卡
E/PATH =:+ /temporary_file.jpg产生java.io.IOException:权限被拒绝
和信息标签
W /系统。 err:java.io.IOException:权限被拒绝
W/System.err:at java.io.UnixFileSystem.createFileE xclusively0(本机方法)
W/System.err的:在 java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
W/System.err的:在java.io.File.createNewFile( File.java:948) W/System.err的:在 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.e rr:at 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。球W/System.err: java.lang.reflect.Method.invoke(Native Method)10-15 20:33:17.912 29759-29759/com.irony.balls W/System.err:at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:874)
10-15 20:33:17.912 29759-29759/com.irony.balls W/System.err的:在 com.android.internal.os.ZygoteInit。主(ZygoteInit。java:764)
你的targetSdk是什么? –
@ H.Brooks'targetSdk'是26 –
是的,那么你将需要运行时权限,解决的办法是将'targetSdk'改为23.因为需要24个运行时权限。 –