Android根据图片path转成Uri,分享图片

先给出代码:

通过uri.fromfile()方法将图片path,转化为uri,然后送给EXTRA_STREAM,实现分享

//分享
                Uri pa=Uri.fromFile(new File(filePath));//根据路径转化为uri
                Intent imageIntent = new Intent(Intent.ACTION_SEND);//调用系统的ACTION_SEND
                imageIntent.setType("image/png");
                imageIntent.putExtra(Intent.EXTRA_STREAM, pa);//EXTRA_STREAM对应转化为uri的path
                startActivity(Intent.createChooser(imageIntent, "分享"));

查看源码fromfile的解释是:

/**
     * Creates a Uri from a file. The URI has the form
     * "file://<absolute path>". Encodes path characters with the exception of
     * '/'.
     *
     * <p>Example: "file:///tmp/android.txt"
     *
     * @throws NullPointerException if file is null
     * @return a Uri for the given file
     */
    public static Uri fromFile(File file) {
        if (file == null) {
            throw new NullPointerException("file");
        }

        PathPart path = PathPart.fromDecoded(file.getAbsolutePath());
        return new HierarchicalUri(
                "file", Part.EMPTY, path, Part.NULL, Part.NULL);
    }

file的解释是:

/**
     * Creates a new <code>File</code> instance by converting the given
     * pathname string into an abstract pathname.  If the given string is
     * the empty string, then the result is the empty abstract pathname.
     *
     * @param   pathname  A pathname string
     * @throws  NullPointerException
     *          If the <code>pathname</code> argument is <code>null</code>
     */
    public File(String pathname) {
        if (pathname == null) {
            throw new NullPointerException();
        }
        this.path = fs.normalize(pathname);
        this.prefixLength = fs.prefixLength(this.path);
    }

EXTRA_STREAM的解释:

/**
     * A content: URI holding a stream of data associated with the Intent,
     * used with {@link #ACTION_SEND} to supply the data being sent.
     */
    public static final String EXTRA_STREAM = "android.intent.extra.STREAM";

顺便给出分享文字的代码,与分享图片差不多:

 Intent textIntent = new Intent(Intent.ACTION_SEND);
                textIntent.setType("text/plain");
                textIntent.putExtra(Intent.EXTRA_TEXT, webView.getUrl().toString());
                startActivity(Intent.createChooser(textIntent, "分享"));

猜你喜欢

转载自blog.csdn.net/mountain_hua/article/details/81224534
今日推荐