2017-10-15 504 views
0

我試圖創建一個映像文件到外部存儲以分享它。但在嘗試下面的代碼我有一些錯誤調用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)

+0

你的targetSdk是什麼? –

+0

@ H.Brooks'targetSdk'是26 –

+1

是的,那麼你將需要運行時權限,解決的辦法是將'targetSdk'改爲23.因爲需要24個運行時權限。 –

回答