Unable to set image source when accessing image from gallery-Android

前端 未结 3 580
-上瘾入骨i
-上瘾入骨i 2021-01-07 06:42

Iam using cordova 3.4. When i capture an image and set it,its working fine but when I try to access on image from gallery I get the url

content://com.androi         


        
3条回答
  •  攒了一身酷
    2021-01-07 07:18

    Whenever some uri is passed into it's implicitly decoded from

    content://com.android.providers.media.documents/document/image%3A9888 (1)

    into

    content://com.android.providers.media.documents/document/image:9888 (2)

    However, after returning from Intent.ACTION_OPEN_DOCUMENT or Intent.ACTION_GET_CONTENT Android provides you with the read permission for (1), not (2). In this case WebView will expectantly log an error:

    java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaDocumentsProvider uri content://com.android.providers.media.documents/document/image:9888 from pid=13163, uid=10165 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission()

    or

    Unable to open content URL

    Code snippet

    All you need to resolve the issue is

        String uriToUseInWebView = transformForWebView(uri.toString());
    
        private String transformForWebView(String uri) {
            for (int i = 0; i < timesDecodingWebView(); i++)
                uri = uri.replace("%", Uri.encode("%"));
            return uri;
        }
    
        private int timesDecodingWebView() {
            if (Build.VERSION.RELEASE.equals("4.4.2")) {
                return 2;
            } else {
                return 1;
            }
        }
    

    in your Java code before passing uri into HTML/JS to ensure that (1) will be actually loaded.

    I've tested that on 4.4.2, 4.4.4 and 5.0. The funny part is that Android 4.4.2 decodes the uri internally twice.

提交回复
热议问题