代码之家  ›  专栏  ›  技术社区  ›  Rajkumar

在whatsapp中共享图像和文本

  •  1
  • Rajkumar  · 技术社区  · 8 年前

    但我无法共享图像,只能共享文本。图像区域显示为空白。
    这是我的密码

    Uri uri = Uri.fromFile(new File(fname));
    Intent share = new Intent();
    share.setAction(Intent.ACTION_SEND);
    share.setPackage("com.whatsapp");
    share.putExtra(Intent.EXTRA_TEXT,ci.description);
    share.putExtra(Intent.EXTRA_STREAM,uri);
    share.setType("image/*");
    share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    try {
       context.startActivity(share);
    }catch (Exception what){
        Toast.makeText(context,"Whatsapp have not been installed",Toast.LENGTH_LONG).show();
    }
    

    这是我的截图

    enter image description here

    有人能帮我吗?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Ranjithkumar    8 年前

    可能是你的URI有问题。。试试这个答案

    意图代码:

                    Intent i = new Intent(Intent.ACTION_SEND);
                        i.setPackage("com.whatsapp");
                        i.setType("image/*");
                        i.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(context, bitmap, id));
                        i.putExtra(Intent.EXTRA_TEXT, text);
                        context.startActivity(Intent.createChooser(i, "Share News"));
    

    位图到URI代码:(如果有文件URI,请跳过此)

    public Uri getLocalBitmapUri(Context context, Bitmap bmp, String id) {
        Uri bmpUri = null;
        try {
            if (id == null) {
                id = String.valueOf(System.currentTimeMillis());
    
            }
            File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + id + ".png");
            FileOutputStream out = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();
            bmpUri = Uri.fromFile(file);
        } catch (Exception e) {
            Log.e(TAG, "getLocalBitmapUri: ", e);
        }
        return bmpUri;
    }