安卓 - 分享到Facebook、Twitter、邮件等

62

我需要开发一个具有分享功能的应用程序。 我必须在Facebook,Twitter,电子邮件和可能是其他服务上分享。

我该如何做? 网上有什么库可以用? 在iOS开发中有ShareKit,但在Android呢?

谢谢 :)


这要看情况。你想分享什么?文字?图片?还是其他的? - iTurki
我需要在图片上发布点击操作,并分享捕获屏幕视图的帖子,以及关于该应用程序链接的分享。 - Harsha
14个回答

88

Paresh Mayani的回答大部分是正确的。只需使用广播意图(Broadcast Intent)来让系统和其他所有应用程序选择以何种方式共享内容。

要分享文本,请使用以下代码:

String message = "Text I want to share.";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, message);

startActivity(Intent.createChooser(share, "Title of the dialog the system will open"));

@Janusz:难道没有直接获取Facebook分享的方法吗?我的意思是不要让系统打开名称列表(Facebook、电子邮件、Twitter等)来选择特定的名称。 - user1161990
1
是的,你可以集成Facebook SDK并直接使用分享选项。但我不建议这样做。这需要很多时间,而且效果还不如这五行代码。 - Janusz
如果我只想在分享列表中显示Twitter和Facebook,因为我不支持其他方式的分享,我该怎么做? - Namratha
1
但是,如果我想区分Twitter和其他应用程序以选择我想要分享的文本,该怎么做? - abeljus
2
列表中出现了许多与分享文本无关的应用程序,如何进行筛选,只显示有意义的应用程序(如短信、Twitter、Facebook、WhatsApp等,而不是一些随机的电子商务应用程序)? - Jasper
显示剩余2条评论

37

是的,你可以...你只需要知道应用程序的确切包名称:

  • Facebook - "com.facebook.katana"
  • Twitter - "com.twitter.android"
  • Instagram - "com.instagram.android"
  • Pinterest - "com.pinterest"

你可以像这样创建意图

Intent intent = context.getPackageManager().getLaunchIntentForPackage(application);
if (intent != null) {
     // The application exists
     Intent shareIntent = new Intent();
     shareIntent.setAction(Intent.ACTION_SEND);
     shareIntent.setPackage(application);

     shareIntent.putExtra(android.content.Intent.EXTRA_TITLE, title);
     shareIntent.putExtra(Intent.EXTRA_TEXT, description);
     // Start the specific social application
     context.startActivity(shareIntent);
} else {
    // The application does not exist
    // Open GooglePlay or use the default system picker
}

它可以工作,但对我来说缺少了shareIntent.setType("type/plain");。 - Teo Inke
每个应用程序的类型可能不同。我建议通过另一种方法动态设置它。 - Ionut Negru
设置类型取决于您想要分享什么。目标应用程序也应支持该类型。为此,您需要在实际环境中进行测试。例如,有些应用程序直接支持图像,而其他应用程序则不支持。 - Ionut Negru
我只想通过设备中所有可用的应用程序共享应用商店链接,如何通过电子邮件、WhatsApp、Facebook和其他消息服务发送链接。 - Harsha

28

我认为您想要添加一个分享按钮,点击它后会出现适合分享的媒体/网站选项。在Android中,您需要创建createChooser来实现这一点。

分享文本:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "This is the text that will be shared.");
startActivity(Intent.createChooser(sharingIntent,"Share using"));

分享二进制对象(图片、视频等)

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(path);

sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));

提醒一下,上面的代码是从在Android中使用ACTION_SEND Intent分享内容参考而来。


1
你的分享文本示例正在分享一张图片。 - Janusz
7
你好,@PareshMayani。我们能够在同一个分享意图中分享图片和文字吗? - Md Maidul Islam
3
@PareshMayani。必须是"text/plain"而不是"plain/text"。我花了一个小时才明白为什么它对我不起作用。 - vvkatwss vvkatwss
你好 @PareshMayani,我能否在单击一个按钮时在两个社交网站上分享一篇帖子?例如,有一个复选框来选择我想要分享帖子的帐户,现在我已经选择了Facebook和Instagram,现在点击按钮后,该帖子应该同时分享到Facebook和Instagram。 - MashukKhan
@MashukKhan,感谢您分享研发主题。实际上,我认为您应该对此进行研究,并在这里分享您的发现 :P - Paresh Mayani
1
@PareshMayani 当然,我已经在做一些针对此事的研究。一旦我找到一些好的内容,我会在这里分享它。 - MashukKhan

6
请使用这个:

使用此

Facebook - "com.facebook.katana"
Twitter - "com.twitter.android"
Instagram - "com.instagram.android"
Pinterest - "com.pinterest"



SharingToSocialMedia("com.facebook.katana")


public void SharingToSocialMedia(String application) {

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_STREAM, bmpUri);

    boolean installed = checkAppInstall(application);
    if (installed) {
        intent.setPackage(application);
        startActivity(intent);
    } else {
        Toast.makeText(getApplicationContext(),
                "Installed application first", Toast.LENGTH_LONG).show();
    }

}


 private boolean checkAppInstall(String uri) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
    }

    return false;
}

1
@BugsHappen 可能是 appInstalledOrNot(application),参考自 https://dev59.com/XWgu5IYBdhLWcg3wWVyF#11392276 - MilapTank
appInstalledOrNot(application) 的意思是检查设备上是否安装了所需的应用程序... - Arslan Maqbool

4

ACTION_SEND适用于所有平台,并且可以将文本主体发送到Twitter、Gmail等应用,但是在Facebook页面上却无法正常使用。这是Facebook Android SDK中已知的一个bug,但他们至今没有修复。


4
ACTION_SEND 对于所有应用都能正常工作,并且可以将文本主体发送到 Twitter、Gmail 等应用,但是在 Facebook 页面上却失败了。这是 Facebook Android SDK 中已知的一个 bug,但他们仍未修复它。 - RAJESH
ACTION_SEND 在 Facebook 和 Facebook Messenger 上运行良好。但是,如果您希望消息的发布显示有意义的缩略图和描述,那么在服务器上准备适当的 OpenGraph 元标签 是值得的。请参阅 https://dev59.com/s3M_5IYBdhLWcg3w-4nw。 - Alex Cohn

4
这将帮助:
1- 首先定义这些常量。
 public static final String FACEBOOK_PACKAGE_NAME = "com.facebook.katana";
    public static final String TWITTER_PACKAGE_NAME = "com.twitter.android";
    public static final String INSTAGRAM_PACKAGE_NAME = "com.instagram.android";
    public static final String PINTEREST_PACKAGE_NAME = "com.pinterest";
    public static final String WHATS_PACKAGE_NAME =  "com.whatsapp";

2- 接下来使用这个方法

 public static void shareAppWithSocial(Context context, String application, String title, 
 String description) {

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setPackage(application);

        intent.putExtra(android.content.Intent.EXTRA_TITLE, title);
        intent.putExtra(Intent.EXTRA_TEXT, description);
        intent.setType("text/plain");

        try {
            // Start the specific social application
            context.startActivity(intent);
        } catch (android.content.ActivityNotFoundException ex) {
            // The application does not exist
            Toast.makeText(context, "app have not been installed.", Toast.LENGTH_SHORT).show();
        }


    }

2

我认为以下代码将会有所帮助...

public void btnShareClick(View v) {
    // shareBtnFlag = 1;
    Dialog d = new Dialog(DrawAppActivity.this);
    d.requestWindowFeature(d.getWindow().FEATURE_NO_TITLE);
    d.setCancelable(true);

    d.setContentView(R.layout.sharing);

    final Button btnFacebook = (Button) d.findViewById(R.id.btnFacebook);
    final Button btnEmail = (Button) d.findViewById(R.id.btnEmail);

    btnEmail.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            if (!btnEmail.isSelected()) {
                btnEmail.setSelected(true);
            } else {
                btnEmail.setSelected(false);
            }
            saveBtnFlag = 1;
            // Check if email id is available-------------
            AccountManager manager = AccountManager
                    .get(DrawAppActivity.this);
            Account[] accounts = manager.getAccountsByType("com.google");
            Account account = CommonFunctions.getAccount(manager);
            if (account.name != null) {
                emailSendingTask eTask = new emailSendingTask();
                eTask.execute();
                if (CommonFunctions.createDirIfNotExists(getResources()
                        .getString(R.string.path)))

                {
                    tempImageSaving(
                            getResources().getString(R.string.path),
                            getCurrentImage());
                }

                Intent sendIntent;
                sendIntent = new Intent(Intent.ACTION_SEND);
                sendIntent.setType("application/octet-stream");
                sendIntent.setType("image/jpeg");
                sendIntent.putExtra(Intent.EXTRA_EMAIL,
                        new String[] { account.name });
                sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Drawing App");
                sendIntent.putExtra(Intent.EXTRA_TEXT, "Check This Image");
                sendIntent.putExtra(Intent.EXTRA_STREAM,
                        Uri.parse("file://" + tempPath.getPath()));

                List<ResolveInfo> list = getPackageManager()
                        .queryIntentActivities(sendIntent,
                                PackageManager.MATCH_DEFAULT_ONLY);

                if (list.size() != 0) {

                    startActivity(Intent.createChooser(sendIntent,
                            "Send Email Using:"));

                }

                else {
                    AlertDialog.Builder confirm = new AlertDialog.Builder(
                            DrawAppActivity.this);
                    confirm.setTitle(R.string.app_name);
                    confirm.setMessage("No Email Sending App Available");
                    confirm.setPositiveButton("Set Account",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    dialog.dismiss();
                                }
                            });
                    confirm.show();
                }
            } else {
                AlertDialog.Builder confirm = new AlertDialog.Builder(
                        DrawAppActivity.this);
                confirm.setTitle(R.string.app_name);
                confirm.setMessage("No Email Account Available!");
                confirm.setPositiveButton("Set Account",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                Intent i = new Intent(
                                        Settings.ACTION_SYNC_SETTINGS);
                                startActivity(i);
                                dialog.dismiss();
                            }
                        });
                confirm.setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {

                                dialog.dismiss();
                            }
                        });
                confirm.show();
            }
        }

    });

    btnFacebook.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            if (!btnFacebook.isSelected()) {
                btnFacebook.setSelected(true);
            } else {
                btnFacebook.setSelected(false);
            }
            saveBtnFlag = 1;
            // if (connection.isInternetOn()) {

            if (android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED)) {
                getCurrentImage();
                Intent i = new Intent(DrawAppActivity.this,
                        FaceBookAuthentication.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivity(i);
            }

            else {
                ShowAlertMessage.showDialog(DrawAppActivity.this,
                        R.string.app_name, R.string.Sd_card,
                        R.string.button_retry);
            }
        }
    });
    d.show();

}

public void tempImageSaving(String tmpPath, byte[] image) {
    Random rand = new Random();

    tempfile = new File(Environment.getExternalStorageDirectory(), tmpPath);
    if (!tempfile.exists()) {
        tempfile.mkdirs();
    }

    tempPath = new File(tempfile.getPath(), "DrawApp" + rand.nextInt()
            + ".jpg");
    try {
        FileOutputStream fos1 = new FileOutputStream(tempPath.getPath());
        fos1.write(image);

        fos1.flush();
        fos1.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    sendBroadcast(new Intent(
            Intent.ACTION_MEDIA_MOUNTED,
            Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}

public byte[] getCurrentImage() {

    Bitmap b = drawingSurface.getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    b.compress(Bitmap.CompressFormat.PNG, 100, stream);

    byteArray = stream.toByteArray();

    return byteArray;
}

private class emailSendingTask extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(DrawAppActivity.this);
        progressDialog.setTitle(R.string.app_name);
        progressDialog.setMessage("Saving..Please Wait..");
        // progressDialog.setIcon(R.drawable.icon);
        progressDialog.show();

    }

    @Override
    protected String doInBackground(String... urls) {

        String response = "";
        try {

            if (android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED)) {

                response = "Yes";

            } else {
                ShowAlertMessage.showDialog(DrawAppActivity.this,
                        R.string.app_name, R.string.Sd_card,
                        R.string.button_retry);

            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return response;

    }

    @Override
    protected void onPostExecute(String result) {

        if (result.contains("Yes")) {
            getCurrentImage();

        }
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://"
                        + Environment.getExternalStorageDirectory())));

        progressDialog.cancel();
    }
}

private class ImageSavingTask extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(DrawAppActivity.this);
        progressDialog.setTitle(R.string.app_name);
        progressDialog.setMessage("Saving..Please Wait..");
        // progressDialog.setIcon(R.drawable.icon);
        progressDialog.show();

    }

    @Override
    protected String doInBackground(String... urls) {

        String response = "";
        try {

            if (android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED)) {

                response = "Yes";

            } else {
                ShowAlertMessage.showDialog(DrawAppActivity.this,
                        R.string.app_name, R.string.Sd_card,
                        R.string.button_retry);

            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return response;

    }

    @Override
    protected void onPostExecute(String result) {

        if (result.contains("Yes")) {
            getCurrentImage();

            if (CommonFunctions.createDirIfNotExists(getResources()
                    .getString(R.string.path)))

            {
                saveImageInSdCard(getResources().getString(R.string.path),
                        getCurrentImage());
            }
        }
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://"
                        + Environment.getExternalStorageDirectory())));

        progressDialog.cancel();
    }
}

使用Facebook SDK来开发Facebook应用程序


你能否完成这段代码?有很多变量和其他函数都缺失了。 - Mahdi Giveie

1

ACTION_SEND 只会提供使用 GMail、YahooMail 等(在您的手机上安装的任何应用程序,可以执行 ACTION_SEND)发送选项。如果您想在 Facebook 或 Twitter 上分享,您需要为每个平台放置自定义按钮,并使用它们自己的 SDK,例如 Facebook SDKTwitter4J


3
这并不正确...ACTION_SEND会打开设备上的任何内容。如果设备上有Facebook和Twitter,则它们将显示为共享选项。 - taraloca
1
无论注册了什么用于ACTION_SEND的应用,它都会创建一个选择器。不能直接使用action_send跳转到Twitter或Facebook。这就是我说的内容。 - Ovidiu Latcu
然而,在Android中更常见的是放置一个全局分享按钮,而不仅仅是FB和Twitter。这只会让事情变得更加复杂,并且也使用户在分享某些内容(例如链接)时拥有更少的选择机会。 - Aitor Gómez
@Wakka,那么如果Facebook对话框无法正常工作,你该如何处理呢?(不会预填文本)。如果必须使用Facebook SDK,则不能将共享对话框用于其他任何内容。 - User
@lxx 抱歉,我不明白你的意思。 - Aitor Gómez

1
创建选择可编辑。
Intent sendIntent = new Intent(Intent.ACTION_SEND);
            sendIntent.setType("text/plain");
            sendIntent.putExtra(Intent.EXTRA_SUBJECT, "My application name");
            String sAux = "\nLet me recommend you this application\n\n";
            sAux = sAux + "https://play.google.com/store/apps/details?id=the.package.id \n\n";
            sendIntent.putExtra(Intent.EXTRA_TEXT, sAux);
            startActivity(Intent.createChooser(sendIntent, "choose one"));

==============================================================

创建选择默认值。
            Intent sendIntent = new Intent(Intent.ACTION_SEND);
            sendIntent.setType("text/plain");
            sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
            startActivity(sendIntent);

=================================================================

多文件发送
发送多个文件,请使用ACTION_SEND_MULTIPLE操作并附上指向文件的URI列表。 MIME类型根据您要共享的内容组合而变化。例如,如果您共享3个JPEG图像,则类型仍为“image/jpeg”。对于各种图像类型的混合物,应该是“image / *”以匹配处理任何类型图像的活动。如果您要共享各种类型,则只应使用“*/*”。如先前所述,解析和处理数据取决于接收应用程序。以下是一个示例:
ArrayList<Uri> imageUris = new ArrayList<Uri>();
imageUris.add(imageUri1); // Add your image URIs here
imageUris.add(imageUri2);

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share images to.."));

================================================================

分享到Facebook
    ShareLinkContent shareLinkContent = new ShareLinkContent.Builder()
            .setQuote("Application of social rating share with your friend")
            .setContentUrl(Uri.parse("https://google.com"))
            .build();
    if (ShareDialog.canShow(ShareLinkContent.class)) {
        sd.show(shareLinkContent);
    }

==============================================================

Share With SMS

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.putExtra("Body", "Application of social rating share with your friend");
    intent.setType("vnd.android-dir/mms-sms");
    startActivity(intent);

==============================================================

分享至电子邮件。
    Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", "", null));
    emailIntent.putExtra(Intent.EXTRA_EMAIL, "Address");
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Application of social rating share with your friend");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "Body");
    startActivity(Intent.createChooser(emailIntent, "Send Email..."));

=============================================================

分享到WhatsApp。
    Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
    whatsappIntent.setType("text/plain");
    whatsappIntent.setPackage("com.whatsapp");
    whatsappIntent.putExtra(Intent.EXTRA_TEXT, "Application of social rating share with your friend");
    try {
        Objects.requireNonNull(getActivity()).startActivity(whatsappIntent);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(getActivity(), "WhatsApp have not been installed.", Toast.LENGTH_SHORT).show();
    }

兄弟,把它更新到所有社交媒体上:Instagram、Linkedin、Twitter... 可能还有其他的,比如Telegram、微信、Signal。 - DragonFire

0
String message = "This is testing."
Intent shareText = new Intent(Intent.ACTION_SEND);
shareText .setType("text/plain");
shareText .putExtra(Intent.EXTRA_TEXT, message);

startActivity(Intent.createChooser(shareText , "Title of the dialog the system will open"));

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