如何与其他应用程序共享图像意图(在whatsApp和其他应用程序中共享图像)?

时间:2019-07-19 12:32:31

标签: android android-intent share

我尝试将图像从我的应用程序共享到其他应用程序,但是显示了敬酒=“文件未发送”。不知道该怎么办。在下面,我已经发布了我用来分享图片的代码

 @Override
    public void onWhatEverClick(int position) {
        Toast.makeText(this, "Normal click at position: " + position, Toast.LENGTH_SHORT).show();
        try {
            Upload selectedItem = mUploads.get(position);

            final String selectedkey = selectedItem.getKey();
            StorageReference imgRef = mStorage.getReferenceFromUrl(selectedItem.getImageUrl());
            String url = selectedItem.getImageUrl();
            String imageString = url.toString();
            URI uri = new URI(imageString);
            final Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("image/jpg");
            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
            startActivity(Intent.createChooser(shareIntent, "Share image using"));
        }


        catch (Exception e)
        {

        }
    }

1 个答案:

答案 0 :(得分:0)

您不能仅使用URL直接共享远程映像,而是需要先下载它,然后才能共享。

执行此操作的“简便”方法是使用PicassoGlide之类的库将文件下载到位图中,将其存储在ExternalFiles中并获取URI然后可以共享文件。

public void shareItem(String url) {
    Picasso.with(getApplicationContext()).load(url).into(new Target() {
        @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("image/*");
            i.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(bitmap));
            startActivity(Intent.createChooser(i, "Share Image"));
        }
        @Override public void onBitmapFailed(Drawable errorDrawable) { }
        @Override public void onPrepareLoad(Drawable placeHolderDrawable) { }
    });
}

public Uri getLocalBitmapUri(Bitmap bmp) {
    Uri bmpUri = null;
    try {
        File file =  new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
        FileOutputStream out = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.close();
        bmpUri = Uri.fromFile(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bmpUri;
}

从此stackoverflow answer引用的示例代码。