Convert file uri to content uri

前端 未结 5 600
暗喜
暗喜 2020-12-06 05:44

i want to choose a file (via file chooser) from astro manager (in my case a *.pdf or *.doc) but the uri contains only the file path (\"sdcard/my_folder/test.pdf\"

相关标签:
5条回答
  • 2020-12-06 06:11

    One simple way to achieve this could be by using MediaScannerConnection

    File file = new File("pathname");
    MediaScannerConnection.scanFile(getContext(), new String[]{file.getAbsolutePath()}, null /*mimeTypes*/, new MediaScannerConnection.OnScanCompletedListener() {
                @Override
                public void onScanCompleted(String s, Uri uri) {
                    // uri is in format content://...
                }
            });
    
    0 讨论(0)
  • 2020-12-06 06:19

    Here is a simpler way to consider, which may be suitable for you.

    I use it for sharing downloaded images on google plus from my android app:

    /**
     * Converts a file to a content uri, by inserting it into the media store.
     * Requires this permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     */
    protected static Uri convertFileToContentUri(Context context, File file) throws Exception {
    
        //Uri localImageUri = Uri.fromFile(localImageFile); // Not suitable as it's not a content Uri
    
        ContentResolver cr = context.getContentResolver();
        String imagePath = file.getAbsolutePath();
        String imageName = null;
        String imageDescription = null;
        String uriString = MediaStore.Images.Media.insertImage(cr, imagePath, imageName, imageDescription);
        return Uri.parse(uriString);
    }
    
    0 讨论(0)
  • 2020-12-06 06:20

    Like @CommmonsWare said, there is no easy way to convert any type of files into content:// .
    But here is how I convert an image File into content://

    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID },
                MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);
    
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-06 06:21

    This works for me and what I use in my Share Folder app:

    1. Create a folder called xml under resources

    2. Add a file_paths.xml to it, with following line in it:

    <files-path name="internal" path="/"/>
    
    1. Add a File provider authority in the manifest, as:
    <provider android:name="android.support.v4.content.FileProvider"
                   android:authorities="com.dasmic.filebrowser.FileProvider"
                   android:windowSoftInputMode="stateHidden|adjustResize"
                   android:exported="false"
                   android:grantUriPermissions="true">
                   <meta-data
                        android:name="android.support.FILE_PROVIDER_PATHS"
                        android:resource="@xml/file_paths" />
    </provider>
    

    4.Transfer file to a different intent with 'content://' as follows:

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //Required for Android 8+
    Uri data = FileProvider.getUriForFile(this, "com.dasmic.filebrowser.FileProvider", file);
    intent.setDataAndType(data, type);
    startActivity(intent);
    
    0 讨论(0)
  • 2020-12-06 06:24

    you can achieve it my using FileProvider

    step 1: create a java file and extends it with FileProvider

    public class MyFileProvider extends FileProvider {
    
    }
    

    step 2: create an xml resource file in res/xml/ directory and copy this code in it

    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
        <external-path name="external_files" path="."/>
    </paths>
    

    step 3: in your manifest file, under <Application> tag add this code

    <provider
                android:name="MyFileProvider" <!-- java file created above -->
                android:authorities="${applicationId}.MyFileProvider"
                android:exported="false"
                android:grantUriPermissions="true">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/provider_paths"/> <!-- xml file created above -->
            </provider>
    

    Step 4: use this code to get Uri in content:// format

    Uri uri = FileProvider.getUriForFile(CameraActivity.this, "your.package.name.MyFileProvider", file /* file whose Uri is required */);
    

    Note: you may need to add read permission

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
    0 讨论(0)
提交回复
热议问题