2017-10-17 97 views
1

我的應用程序允許用戶查看圖庫或其他位置中的某些選定圖像。我請求通過URI的圖像:重新啓動後圖庫中的圖像權限丟失

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); 
photoPickerIntent.setType("image/*"); 
startActivityForResult(photoPickerIntent, PickerFragment.PICK_PHOTO); 

然後得到URI在onActivityResult(INT requestCode,INT resultCode爲,意圖數據),並有機會獲得這些圖像把它們放在我的應用程序的意見通過:

Uri imageUri= data.getData(); 

當應用程序完成後,我保存所有的URI在我的數據庫通過字符串:

String imageUriString = imageUri.toString(); 
saveToDB (imageUriString); 

然而,當我重新啓動應用程序,並從我的DAT恢復所有的URI通過:

String imageUriString = restoreFromDB(); 
imageUri = Uri.parse (imageUriString); 

該應用程序沒有權限的那些Uri的在Android 7.1中。 我通過訪問圖片:

ContentResolver cr = mContext.getContentResolver(); 
InputStream is = cr.openInputStream(imageUri); 
BitmapFactory.decodeStream(is, null, o); 

但收到此異常:

java.lang.SecurityException: Permission Denial: opening provider com.google.android.apps.photos.contentprovider.impl.MediaContentProvider from ProcessRecord 

有一種優雅的和合法的方式來保持該權限? 我試圖閱讀關於權限的所有文檔,但感覺真的很困惑。

如果你讓我正確的學習方向,將不勝感激。

PS Uri的權限持續時,將圖像複製到應用程序內存是一種選擇,但我想避免這種情況。至少看看是否有可能。

PPS我已授予所有權限,例如相機和外部存儲器寫入和讀取。

+0

檢查時圖像不存在此鏈接https://stackoverflow.com/questions/37409181/java-lang-securityexception-permission-denial-opening-provider – Anonymous

+0

店字節組而不是uri.Uri失敗在畫廊。 – Anonymous

+0

@匿名,存儲是一個選項,但不是理想的。在我的情況下,即使圖像存在於圖庫中,Uri也會失敗 – rommex

回答

1

所以,在@greenapps的重要幫助和測試之後荷蘭國際集團在模擬器和實際設備,該解決方案是這樣的:

  • 使用的另一種意圖:

    意圖photoPickerIntent =新意圖(Intent.ACTION_OPEN_DOCUMENT);

  • 在onActivityResult

    ()固定爲URI中的持久化權限,這將是應用程序的重新發布後完好無損:

    烏里selectedImage = data.getData();

    if(Build.VERSION.SDK_INT> Build.VERSION_CODES。JELLY_BEAN_MR2)getContentResolver()。takePersistableUriPermission(selectedImage,Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); }

0

是指回答here

打開使用對話框下面的代碼:

ActivityCompat.requestPermissions(MainActivity.this, 
        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 
        1); 

獲得如下的活動結果:

@Override 
public void onRequestPermissionsResult(int requestCode, 
             String permissions[], int[] grantResults) { 
    switch (requestCode) { 
     case 1: { 

      // If request is cancelled, the result arrays are empty. 
      if (grantResults.length > 0 
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

       // permission was granted, yay! Do the 
       // contacts-related task you need to do.   
      } else { 

       // permission denied, boo! Disable the 
       // functionality that depends on this permission. 
       Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show(); 
      } 
      return; 
     } 

     // other 'case' lines to check for other 
     // permissions this app might request 
    } 
} 

更多信息:https://developer.android.com/training/permissions/requesting.html

+0

我已授予所有權限,例如相機和外部存儲器的寫入和讀取。我的問題是關於另一個問題。 – rommex

+0

那麼在答案中使用的代碼是肯定的? –

+0

問題是關於文件Uri權限,而不是一般運行時權限。 – rommex