从另一个应用程序获取路径(WhatsApp)

时间:2017-06-09 19:42:37

标签: android path uri whatsapp

我没有从whatsApp收到的来自uri的图片或视频获取路径。

Uri是这样的:content://com.whatsapp.provider.media/item/16695

来自Gallery,Downloads和其他人的媒体很好。

任何人都知道如何获得Path?这是我正在使用的代码:

public String getMediaPath(Context context, Uri uri) {

    if (DEBUG)
        Log.d(TAG + " File -",
                "Authority: " + uri.getAuthority() +
                        ", Fragment: " + uri.getFragment() +
                        ", Port: " + uri.getPort() +
                        ", Query: " + uri.getQuery() +
                        ", Scheme: " + uri.getScheme() +
                        ", Host: " + uri.getHost() +
                        ", Segments: " + uri.getPathSegments().toString()
        );

    // DocumentProvider
    if (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];
            }


        }
        // 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)) {
            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 the remote address
        if (isGooglePhotosUri(uri)) {
            return uri.getLastPathSegment();
        }

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;

}

public String getDataColumn(Context context, Uri uri, String selection,
                            String[] selectionArgs) {

    Cursor cursor = null;
    final String[] column = { MediaStore.Images.Media.DATA };
    final String[] projection = {
            column[0]
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            if (DEBUG)
                DatabaseUtils.dumpCursor(cursor);

            final int index = cursor.getColumnIndexOrThrow(column[0]);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

public static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.contentprovider".equals(uri.getAuthority());
}

此日志的结果:

    if (DEBUG)
    Log.d(TAG + " File -",
            "Authority: " + uri.getAuthority() +
                    ", Fragment: " + uri.getFragment() +
                    ", Port: " + uri.getPort() +
                    ", Query: " + uri.getQuery() +
                    ", Scheme: " + uri.getScheme() +
                    ", Host: " + uri.getHost() +
                    ", Segments: " + uri.getPathSegments().toString()
    );

就是这样:

Authority: com.whatsapp.provider.media, Fragment: null, Port: -1, Query: null, Scheme: content, Host: com.whatsapp.provider.media, Segments: [item, 16348]

getDataColumn上的光标如下所示:

>>>>> Dumping cursor 
android.content.ContentResolver$CursorWrapperInner@1fc81ac
I/System.out: 0 {
I/System.out: }
I/System.out: <<<<<

7 个答案:

答案 0 :(得分:1)

你可以试试这个,然后你得到一个选定图像的位图,然后你就可以从设备默认图库中轻松找到它的原生路径。

Bitmap roughBitmap= null;
    try {
    // Works with content://, file://, or android.resource:// URIs
    InputStream inputStream =
    getContentResolver().openInputStream(uri);
    roughBitmap= BitmapFactory.decodeStream(inputStream);

    // calc exact destination size
    Matrix m = new Matrix();
    RectF inRect = new RectF(0, 0, roughBitmap.Width, roughBitmap.Height);
    RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
    m.SetRectToRect(inRect, outRect, Matrix.ScaleToFit.Center);
    float[] values = new float[9];
    m.GetValues(values);


    // resize bitmap if needed
    Bitmap resizedBitmap = Bitmap.CreateScaledBitmap(roughBitmap, (int) (roughBitmap.Width * values[0]), (int) (roughBitmap.Height * values[4]), true);

    string name = "IMG_" + new Java.Text.SimpleDateFormat("yyyyMMdd_HHmmss").Format(new Java.Util.Date()) + ".png";
    var sdCardPath= Environment.GetExternalStoragePublicDirectory("DCIM").AbsolutePath;
    Java.IO.File file = new Java.IO.File(sdCardPath);
    if (!file.Exists())
    {
        file.Mkdir();
    }
    var filePath = System.IO.Path.Combine(sdCardPath, name);
    } catch (FileNotFoundException e) {
    // Inform the user that things have gone horribly wrong
    }

答案 1 :(得分:1)

您无法从WhatsApp获取文件路径。他们现在不暴露它。你唯一能得到的是InputStream is = getContentResolver().openInputStream(Uri.parse("content://com.whatsapp.provider.media/item/16695"));

is

使用@IBOutlet var buttons: [UIButton]! ,您可以在应用中显示WhatsApp的图片。

答案 2 :(得分:0)

如果要将照片上传到服务器,还可以将URI转换为文件,然后转换为字节。

  

退房:https://www.stackoverflow.com/a/49575321

答案 3 :(得分:0)

使用下面的代码示例将返回位图:

BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.parse("content://com.whatsapp.provider.media/item/128752")))

之后你们都知道你必须做什么。

答案 4 :(得分:0)

它适用于我打开小文本文件...我没有尝试过其他文件

protected void viewhelper(Intent intent) {
    Uri a = intent.getData();
    if (!a.toString().startsWith("content:")) {
        return;
    }
    //Ok Let's do it
    String content = readUri(a);
    //do something with this content
}

这是readUri(Uri uri)方法

private String readUri(Uri uri) {
    InputStream inputStream = null;
    try {
        inputStream = getContentResolver().openInputStream(uri);
        if (inputStream != null) {
            byte[] buffer = new byte[1024];
            int result;
            String content = "";
            while ((result = inputStream.read(buffer)) != -1) {
                content = content.concat(new String(buffer, 0, result));
            }
            return content;
        }
    } catch (IOException e) {
        Log.e("receiver", "IOException when reading uri", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Log.e("receiver", "IOException when closing stream", e);
            }
        }
    }
    return null;
}

我是从此存储库https://github.com/zhutq/android-file-provider-demo/blob/master/FileReceiver/app/src/main/java/com/demo/filereceiver/MainActivity.java中获得的
我修改了一些代码以使其正常工作。

清单文件:

    <activity android:name=".MainActivity">
        <intent-filter >
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="*/*" />
        </intent-filter>
    </activity>

您需要添加

@Override
protected void onCreate(Bundle savedInstanceState) {
    /*
     *    Your OnCreate
     */
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    //VIEW"
    if (Intent.ACTION_VIEW.equals(action) && type != null) {
        viewhelper(intent); // Handle text being sent
    }
  }

答案 5 :(得分:0)

您可以尝试使用此方法为您提供帮助。您无法直接从WhatsApp获取路径。如果需要文件路径,请先复制文件并发送新文件路径。 使用下面的代码

 public static String getFilePathFromURI(Context context, Uri contentUri) {
    String fileName = getFileName(contentUri);
    if (!TextUtils.isEmpty(fileName)) {
        File copyFile = new File(TEMP_DIR_PATH  + fileName+".jpg");
        copy(context, contentUri, copyFile);
        return copyFile.getAbsolutePath();
    }
    return null;
}

public static String getFileName(Uri uri) {
    if (uri == null) return null;
    String fileName = null;
    String path = uri.getPath();
    int cut = path.lastIndexOf('/');
    if (cut != -1) {
        fileName = path.substring(cut + 1);
    }
    return fileName;
}

public static void copy(Context context, Uri srcUri, File dstFile) {
    try {
        InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
        if (inputStream == null) return;
        OutputStream outputStream = new FileOutputStream(dstFile);
        IOUtils.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

然后,IOUtils类如下所示

public class IOUtils {



private static final int BUFFER_SIZE = 1024 * 2;

private IOUtils() {
    // Utility class.
}

public static int copy(InputStream input, OutputStream output) throws Exception, IOException {
    byte[] buffer = new byte[BUFFER_SIZE];

    BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
    BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
    int count = 0, n = 0;
    try {
        while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
            out.write(buffer, 0, n);
            count += n;
        }
        out.flush();
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            Log.e(e.getMessage(), e.toString());
        }
        try {
            in.close();
        } catch (IOException e) {
            Log.e(e.getMessage(), e.toString());
        }
    }
    return count;
}


}

答案 6 :(得分:0)

受保护的void onCreate(Bundle savedInstanceState){ / * *您的OnCreate * / 意图意图= getIntent(); 字符串操作= intent.getAction(); 字符串类型= intent.getType();

//VIEW"
if (Intent.ACTION_VIEW.equals(action) && type != null) {viewhekper(intent);//Handle text being sent}