Android Intent Share 使用外部图片 url

标签 android android-intent share

我不禁注意到所有使用 Intent 共享图像的示例都使用本地存储的文件。 每当我尝试使用外部 url 时,facebook、twitter 等都会给我 toast “无法添加一个或多个媒体项目”。

我是否必须在本地存储图像的副本?如果是,我该怎么做?

最佳答案

感谢@user2245247 link
它包含从远程 url 共享图像的正确答案。
使用外部库

// Get access to ImageView 
ImageView ivImage = (ImageView) findViewById(R.id.ivResult);
// Fire async request to load image
Picasso.with(context).load(imageUrl).into(ivImage);

图片成功加载到图片 View 后,触发分享 Intent 的方法。

// Can be triggered by a view event such as a button press
public void onShareItem(View v) {
    // Get access to bitmap image from view
    ImageView ivImage = (ImageView) findViewById(R.id.ivResult);
    // Get access to the URI for the bitmap
    Uri bmpUri = getLocalBitmapUri(ivImage);
    if (bmpUri != null) {
        // Construct a ShareIntent with link to image
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
        shareIntent.setType("image/*");
        // Launch sharing dialog for image
        startActivity(Intent.createChooser(shareIntent, "Share Image"));    
    } else {
        // ...sharing failed, handle error
    }
}

// Returns the URI path to the Bitmap displayed in specified ImageView
public Uri getLocalBitmapUri(ImageView imageView) {
    // Extract Bitmap from ImageView drawable
    Drawable drawable = imageView.getDrawable();
    Bitmap bmp = null;
    if (drawable instanceof BitmapDrawable){
       bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    } else {
       return null;
    }
    // Store image to default external storage directory
    Uri bmpUri = null;
    try {
        File file =  new File(Environment.getExternalStoragePublicDirectory(  
            Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
        file.getParentFile().mkdirs();
        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;
}

确保您已获得以下权限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

关于Android Intent Share 使用外部图片 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26301170/

相关文章:

java - 我如何在我的应用程序中共享 apk 文件(发送应用程序本身)

java - 在多个属性中搜索一个值

android - StartActivityForResult 未将数据返回给父 Activity

android - 从 Flutter 插件获取 v4.app.FragmentManager

android - 为什么 FLAG_ACTIVITY_CLEAR_TOP 不起作用?

android - 检查设备是否可以调用电话

swift - GameScene 分享按钮

windows-8 - 如何在 WinRt 中共享文本时添加新行

java - 无法显示来自 Intent 的字符串

android - 将通知 ID 发送到每个通知的 Activity