retrieve absolute path when select image from gallery kitkat android

前端 未结 4 1331
说谎
说谎 2020-12-01 07:59

As I am supporting my app to Kitkat version, now in this the way of retrieve file from gallery was different.

I have preferred this Android Gallery on KitKat returns

4条回答
  •  無奈伤痛
    2020-12-01 08:40

    Here is one way to access the Absolute path after selecting file.

    After getting data in new URI format for KK(KitKat) like this way

    content://com.android.providers.media.documents/document/image:2505
    

    Just extract ID of your document

    if(requestCode == GALLERY_KITKAT_INTENT_CALLED && resultCode == RESULT_OK){
    
        Uri originalUri = data.getData();
    
        final int takeFlags = data.getFlags()
                            & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        // Check for the freshest data.
        getContentResolver().takePersistableUriPermission(originalUri, takeFlags);
    
        /* now extract ID from Uri path using getLastPathSegment() and then split with ":"
        then call get Uri to for Internal storage or External storage for media I have used getUri()
        */
    
        String id = originalUri.getLastPathSegment().split(":")[1]; 
        final String[] imageColumns = {MediaStore.Images.Media.DATA };
        final String imageOrderBy = null;
    
        Uri uri = getUri();
        String selectedImagePath = "path";
    
        Cursor imageCursor = managedQuery(uri, imageColumns,
              MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
    
        if (imageCursor.moveToFirst()) {
            selectedImagePath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
        }
        Log.e("path",selectedImagePath ); // use selectedImagePath 
    }else if() {
          // for older version use existing code here
    }
    
    // By using this method get the Uri of Internal/External Storage for Media
    private Uri getUri() {
        String state = Environment.getExternalStorageState();
        if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
            return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
    
        return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    }
    

提交回复
热议问题