Android 如何处理不同类型的内容uri

Android 如何处理不同类型的内容uri,android,share-intent,Android,Share Intent,我想从另一个应用程序中获取图像URI,比如gallery、google drive、whats应用程序等 我已注册以下意向过滤器: <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT"/>

我想从另一个应用程序中获取图像URI,比如gallery、google drive、whats应用程序等

我已注册以下意向过滤器:

        <intent-filter>
            <action android:name="android.intent.action.SEND" />
            <category android:name="android.intent.category.DEFAULT"/>
            <data android:mimeType="image/*" />
        </intent-filter>
有了这个,我可以从gallery whats应用程序中查看我的应用程序。从gallery中,我可以获得图像路径URI,但当我试图从其他应用程序(如whatsapp或google drive)共享时,它会给我空值
如何从不同类型的应用程序获取路径查看此信息可能会有所帮助

在舱单中:

  <activity android:name=".ui.MyActivity" >
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="image/*" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.SEND_MULTIPLE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="image/*" />
    </intent-filter>
</activity>

有关更多信息,请检查:

获取contentURI后,可以使用以下方法获取实际Uri,方法如下

// You can use call the method from your activity like this.
String path = getPath(this,contentURI);

//This the method to get the actual path from the uri
public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
if (isGoogleDriveUri(uri)) {
                return getDriveFilePath(uri, context);
}
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return uri.getPath();
    }

    /**
     * Method to check if the uri is external storage document
     *
     * @param uri uri
     * @return true if the uri authority is of external storage
     */
    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * Method to download the document
     *
     * @param uri uri
     * @return true if uri is of type download documents
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * Get the value of the data column for this Uri.
     */
    private static String getDataColumn(Context context, Uri uri, String selection,
                                        String[] selectionArgs) {
        final String column = "_data";
        final String[] projection = {
                column
        };
        try (Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null)) {
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        }
        return null;
    }

// isGoogleDriveUri method 

  private static boolean isGoogleDriveUri(Uri uri) {
        return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
    }

//getDriveFilePath method 
 private static String getDriveFilePath(Uri uri, Context context) {
        Uri returnUri = uri;
        Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
        /*
         * Get the column indexes of the data in the Cursor,
         *     * move to the first row in the Cursor, get the data,
         *     * and display it.
         * */
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
        returnCursor.moveToFirst();
        String name = (returnCursor.getString(nameIndex));
        String size = (Long.toString(returnCursor.getLong(sizeIndex)));
        File file = new File(context.getCacheDir(), name);
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            FileOutputStream outputStream = new FileOutputStream(file);
            int read = 0;
            int maxBufferSize = 1 * 1024 * 1024;
            int bytesAvailable = inputStream.available();

            //int bufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);

            final byte[] buffers = new byte[bufferSize];
            while ((read = inputStream.read(buffers)) != -1) {
                outputStream.write(buffers, 0, read);
            }
            Log.e("File Size", "Size " + file.length());
            inputStream.close();
            outputStream.close();
            Log.e("File Path", "Path " + file.getPath());
            Log.e("File Size", "Size " + file.length());
        } catch (Exception e) {
            Log.e("Exception", e.getMessage());
        }
        return file.getPath();
    }
//对于whatsapp,您可以使用: //whatsapp以这种特殊方式返回uri-content://com.whatsapp.provider.media/item/xxxxx

InputStream is = getContentResolver().openInputStream(uri);
现在,您必须使用此输入流获取文件路径。然后你必须从输入流中读取数据

您可能需要将其添加到最后一个if-else块中,如:-

if ("content".equalsIgnoreCase(uri.getScheme())) {
            String path = "";
            try{
                path = getDataColumn(context, uri, null, null);
            }catch (Exception e){
                try {
                    InputStream is = context.getContentResolver().openInputStream(uri);
                    //TODO: read this input stream to get data
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }
            }
            return path;
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            String path = "";
            try{
                path = uri.getPath();
            }catch (Exception e){
                try {
                    InputStream is = context.getContentResolver().openInputStream(uri);
                    //TODO: read this input stream to get data
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }
            }
            return path;
        }

你的问题不清楚。你想从其他应用程序中选择任何图像,还是想将你的应用程序的图像共享给其他应用程序?我将从其他应用程序中共享图像,我的应用程序将接收图像,例如从google drive接收图像。你可以在什么应用程序上共享图像。它提供的内容uri不是实际的uri。它可以在gallery上运行,但不能在google drive或其他应用程序上运行。What abt whats应用程序和其他应用程序,如telegramits,为其他应用程序提供null。我们必须检查这些应用程序是否公开了路径,如果它们公开了路径,那么您必须检查每种类型的内容URI,如公共下载中使用的URI,否则,如果他们返回inputstream,则您必须通过inputstream获取文件。我已更新了whatsapp的答案,但您必须检查应用程序是否公开路径。如果应用程序公开了路径,您可以通过指定内容uri来获取路径,如果应用程序公开了输入流,那么您必须读取输入流以获取其他应用程序(如telegram、dropbox)的数据相同逻辑?
InputStream is = getContentResolver().openInputStream(uri);
if ("content".equalsIgnoreCase(uri.getScheme())) {
            String path = "";
            try{
                path = getDataColumn(context, uri, null, null);
            }catch (Exception e){
                try {
                    InputStream is = context.getContentResolver().openInputStream(uri);
                    //TODO: read this input stream to get data
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }
            }
            return path;
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            String path = "";
            try{
                path = uri.getPath();
            }catch (Exception e){
                try {
                    InputStream is = context.getContentResolver().openInputStream(uri);
                    //TODO: read this input stream to get data
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }
            }
            return path;
        }