通过WhatsApp或Facebook分享图像和文本

30

我的应用程序中有一个分享按钮,我想同时分享一张图像和一段文本。在 Gmail 中,这很好用,但在 WhatsApp 中,只发送了图像,在 Facebook 上,该应用程序崩溃了。

我用于分享的代码如下:

Intent shareIntent = new Intent(Intent.ACTION_SEND);  
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Message");         

Uri uri = Uri.parse("android.resource://" + getPackageName() + "/drawable/ford_focus_2014");
     try {
        InputStream stream = getContentResolver().openInputStream(uri);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

shareIntent.putExtra(Intent.EXTRA_STREAM, uri);

如果我使用“shareIntent.setType(“*/ *” )”,Facebook和WhatsApp会崩溃。

有没有什么办法可以做到这一点?也许可以同时通过两条消息来发送(WhatsApp)。

提前致谢。


可能是Android如何使用Intent发送文本、图像或任何对象?的重复问题。 - Shabbir Dhangot
这个链接有很多关于此的示例 https://github.com/codepath/android_guides/wiki/Sharing-Content-with-Intents - Charleston
12个回答

39

目前Whatsapp支持同时分享图像和文本(截至2014年11月)。

以下是如何进行此操作的示例:

    /**
     * Show share dialog BOTH image and text
     */
    Uri imageUri = Uri.parse(pictureFile.getAbsolutePath());
    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    //Target whatsapp:
    shareIntent.setPackage("com.whatsapp");
    //Add text and then Image URI
    shareIntent.putExtra(Intent.EXTRA_TEXT, picture_text);
    shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
    shareIntent.setType("image/jpeg");
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    try {
        startActivity(shareIntent);
    } catch (android.content.ActivityNotFoundException ex) {
        ToastHelper.MakeShortText("Whatsapp have not been installed.");
    }

1
视频配字幕呢? - yarin
1
我尝试了上面的代码,但它没有起作用,显示“共享失败,请稍后再试”。 - Snehangshu Kar
可以!我们可以为每个图像单独设置标题吗? - Reejesh PK
Uri.parse(pictureFile.getAbsolutePath()) will throw exception on marshmallow and later as you need to declare your FileProvider inside the Manifest.xml file then call it link this: Uri imageUri = FileProvider.getUriForFile( context, context.getPackageName() + ".provider", new File(pictureFile.getAbsolutePath())) - blueware
PHP 有类似的选项吗? - Android Rao
1
当号码没有保存在联系人中时,如何使用? - Abhishek

31
请尝试下面的代码,希望它能够正常工作。
    Uri imgUri = Uri.parse(pictureFile.getAbsolutePath());
    Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
    whatsappIntent.setType("text/plain");
    whatsappIntent.setPackage("com.whatsapp");
    whatsappIntent.putExtra(Intent.EXTRA_TEXT, "The text you wanted to share");
    whatsappIntent.putExtra(Intent.EXTRA_STREAM, imgUri);
    whatsappIntent.setType("image/jpeg");
    whatsappIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    try {
        activity.startActivity(whatsappIntent);
    } catch (android.content.ActivityNotFoundException ex) {
        ToastHelper.MakeShortText("Whatsapp have not been installed.");
    }

2
请查看下面的答案,它使得分享变得更加容易。 - Darpan
@ShaniGoriwal 我有一个自定义的应用程序列表视图,可以在其中共享数据,但是我如何使用 getLaunchIntentForPackage(String pckg) 共享数据? - Devendra Singh
可以通过传递Intent.EXTRA_STREAM和imageUri发送。 - Prasanna Anbazhagan
@ShaniGoriwal 我在 Android 的 drawable 中使用了 "image/*" 或者 "image/specific_format" 来分享图片,但是却遇到了 "文件格式不支持" 的错误提示。请问需要设置权限或做其他的操作吗? - Karthikeyan Ve
下面的答案说得不对,正确的是应该向上。 - AwaisMajeed
显示剩余3条评论

9

如果需要在WhatsApp上分享文本图片,可以使用下面更加可控的代码版本,您还可以添加更多方法来与TwitterFacebook等平台分享...

public class IntentShareHelper {

    public static void shareOnWhatsapp(AppCompatActivity appCompatActivity, String textBody, Uri fileUri) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.setPackage("com.whatsapp");
        intent.putExtra(Intent.EXTRA_TEXT,!TextUtils.isEmpty(textBody) ? textBody : "");

        if (fileUri != null) {
            intent.putExtra(Intent.EXTRA_STREAM, fileUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setType("image/*");
        }

        try {
            appCompatActivity.startActivity(intent);
        } catch (android.content.ActivityNotFoundException ex) {
            ex.printStackTrace();
            showWarningDialog(appCompatActivity, appCompatActivity.getString(R.string.error_activity_not_found));
        }
    }

    public static void shareOnTwitter(AppCompatActivity appCompatActivity, String textBody, Uri fileUri){...}

    private static void showWarningDialog(Context context, String message) {
        new AlertDialog.Builder(context)
                .setMessage(message)
                .setNegativeButton(context.getString(R.string.close), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setCancelable(true)
                .create().show();
    }
}

要从文件获取 Uri,请使用以下类:

public class UtilityFile {
    public static @Nullable Uri getUriFromFile(Context context, @Nullable File file) {
        if (file == null)
            return null;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                return FileProvider.getUriForFile(context, "com.my.package.fileprovider", file);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return Uri.fromFile(file);
        }
    }

    // Returns the URI path to the Bitmap displayed in specified ImageView       
    public static Uri getLocalBitmapUri(Context context, ImageView imageView) {
        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 {
            // Use methods on Context to access package-specific directories on external storage.
            // This way, you don't need to request external read/write permission.
            File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
            FileOutputStream out = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();

            bmpUri = getUriFromFile(context, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bmpUri;
    }    
}

如果要编写FileProvider,请使用此链接:https://github.com/codepath/android_guides/wiki/Sharing-Content-with-Intents


如果我们从现有的位图中获取位图,会怎样呢?https://stackoverflow.com/questions/27835607/how-can-i-send-bitmap-to-whatsapp-application 我们可以附加它吗?因为我不想在目录中写文件。 - gumuruh

2

目前,Whatsapp Intent 支持图像和文本:

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT,title + "\n\nLink : " + link );
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(sharePath));
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share image via:"));

图像将保持原样,EXTRA_TEXT 将显示为标题。

截至2016年2月,工作正常。 - Akhil Sekharan
1
如果我想分享给未保存的联系人怎么办?这可行吗? - gumuruh

1
尝试使用这段代码。
    Uri imageUri = Uri.parse(Filepath);
    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.setPackage("com.whatsapp");
    shareIntent.putExtra(Intent.EXTRA_TEXT, "My sample image text");
    shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
    shareIntent.setType("image/jpeg");
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    
    try {
        startActivity(shareIntent);
    } catch (android.content.ActivityNotFoundException ex) {
        ToastHelper.MakeShortText("Kindly install whatsapp first");
    }

感谢您提供这段代码片段,它可能会立即提供一些帮助。通过展示为什么这是一个好的解决方案,适当的解释将极大地提高其教育价值,并使其对未来具有类似但不完全相同问题的读者更有用。请编辑您的答案以添加解释,并指出适用的限制和假设。 - Toby Speight

0
public void shareIntentSpecificApps(String articleName, String articleContent, String imageURL) {
    List<Intent> intentShareList = new ArrayList<Intent>();
    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    //shareIntent.setType("image/*");
    List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(shareIntent, 0);

    for (ResolveInfo resInfo : resolveInfoList) {
        String packageName = resInfo.activityInfo.packageName;
        String name = resInfo.activityInfo.name;
        Log.d("System Out", "Package Name : " + packageName);
        Log.d("System Out", "Name : " + name);

        if (packageName.contains("com.facebook") ||
                packageName.contains("com.whatsapp")) {


            Intent intent = new Intent();
            intent.setComponent(new ComponentName(packageName, name));
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_SUBJECT, articleName);
            intent.putExtra(Intent.EXTRA_TEXT, articleName + "\n" + articleContent);
            Drawable dr = ivArticleImage.getDrawable();
            Bitmap bmp = ((GlideBitmapDrawable) dr.getCurrent()).getBitmap();
            intent.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(bmp));
            intent.setType("image/*");
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intentShareList.add(intent);
        }
    }

    if (intentShareList.isEmpty()) {
        Toast.makeText(ArticleDetailsActivity.this, "No apps to share !", Toast.LENGTH_SHORT).show();
    } else {
        Intent chooserIntent = Intent.createChooser(intentShareList.remove(0), "Share Articles");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentShareList.toArray(new Parcelable[]{}));
        startActivity(chooserIntent);
    }
}

你也可以分享图片,就像上面的代码中所提到的那样,在我的应用程序中完成了。


0
实际上,可以通过将图像下载到设备的外部存储器,然后将图像分享到WhatsApp来发送图像和文本。
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {

    Bitmap bm = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    Intent intent = new Intent(Intent.ACTION_SEND);
    String share_text = "image and text";
    intent.putExtra(Intent.EXTRA_TEXT, notification_share);
    String path = MediaStore.Images.Media.insertImage(MainActivity.this.getContentResolver(), bm, "", null);
    Uri screenshotUri = Uri.parse(path);

    intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
    intent.setType("image/*");
    startActivity(Intent.createChooser(intent, "Share image via..."));
} else {
    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
//The above code works perfect need to show image in an imageView

0

使用此代码在WhatsApp或其他带有图像和视频的应用程序上进行共享。这里的URI是图像的路径。如果图像在内存中,则加载速度快,如果您使用的是URL,则有时图像不会加载并且链接会直接消失。

shareBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    uri1=Uri.parse(Paths+File.separator+Img_name);
                    Intent intent=new Intent(Intent.ACTION_SEND);
                    intent.setType("image/*");
                    //intent.putExtra(intent.EXTRA_SUBJECT,"Insert Something new");
                    String data = "Hello";
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.putExtra(Intent.EXTRA_TEXT,data);
                    intent.putExtra(Intent.EXTRA_STREAM,uri1);
                    intent.setPackage("com.whatsapp");

                    startActivity(intent);

                    // end Share code
                }

如果这段代码不容易理解,可以查看我在另一个答案中的完整代码。

0

我对这个问题的第二个答案是:我在这里粘贴完整的代码,因为新开发人员有时需要完整的代码。

public class ImageSharer extends AppCompatActivity {
    private ImageView imgView;
    private Button shareBtn;
    FirebaseStorage fs;
    StorageReference sr,sr1;
    String Img_name;
    File dir1;
    Uri uri1;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_sharer);
        imgView = (ImageView) findViewById(R.id.imgView);
        shareBtn = (Button) findViewById(R.id.shareBtn);

        // Initilize firebasestorage instance
        fs=FirebaseStorage.getInstance();
        sr=fs.getReference();
        Img_name="10.jpg";
        sr1=sr.child("shiva/"+Img_name);
        final String Paths= Environment.getExternalStorageDirectory()+ File.separator+"The_Bhakti"+File.separator+"Data";
dir1=new File(Paths);
if(!dir1.isDirectory())
{
    dir1.mkdirs();
}
   sr1.getFile(new File(dir1,Img_name)).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
       @Override
       public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
           sr1.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
               @Override
               public void onSuccess(Uri uri) {
                   uri1= Uri.parse(uri.toString());
               }
           });

       }
   }) ;

        shareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                uri1=Uri.parse(Paths+File.separator+Img_name);
                Intent intent=new Intent(Intent.ACTION_SEND);
                intent.setType("image/*");
                //intent.putExtra(intent.EXTRA_SUBJECT,"Insert Something new");
                String data = "Hello";
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.putExtra(Intent.EXTRA_TEXT,data);
                intent.putExtra(Intent.EXTRA_STREAM,uri1);
                intent.setPackage("com.whatsapp");
                // for particular choose we will set getPackage()
                /*startActivity(intent.createChooser(intent,"Share Via"));*/// this code use for universal sharing
                startActivity(intent);

                // end Share code
            }
        });

    }// onCreate closer
}

0
这个可以使用:
    <activity android:name="com.selcuksoydan.sorucevap.Main">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <action android:name="android.intent.action.SEND" />
            <data android:mimeType="image/*" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

        soru_image = (ImageView) soruView.findViewById(R.id.soru_image);
       soru_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    v.buildDrawingCache();
                    Bitmap bitmap =   v.getDrawingCache();
                    String root = Environment.getExternalStorageDirectory().toString();
                    File myDir = new File(root + "/SoruCevap");
                    Random generator = new Random();
                    int n = 10000;
                    n = generator.nextInt(n);
                    String fname = "Image-" + n + ".jpg";
                    File file = new File(myDir, fname);
                    if (file.exists()) file.delete();
                    try {
                        FileOutputStream out = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                        out.flush();
                        out.close();
                    } catch (Exception ex) {
                        //ignore
                    }
                    Intent waIntent = new Intent(Intent.ACTION_SEND);
                    waIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    waIntent.setType("image/*");
                    waIntent.setPackage("com.whatsapp");
                    waIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.fromFile(file));
                    getContext().startActivity(Intent.createChooser(waIntent, "Share with"));
                } catch (Exception e) {
                    Log.e("Error on sharing", e + " ");
                    Toast.makeText(getContext(), "App not Installed", Toast.LENGTH_SHORT).show();
                }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接