Android:如何通过意图在 facebook 上与文本共享图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22533773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:09:13  来源:igfitidea点击:

Android: How to share image with text on facebook via intent?

androidfacebookandroid-intent

提问by Mansi

I'd like to share a photo with caption pre-filled from my app via a share intent, on facebook.

我想通过分享意图在 facebook 上分享一张从我的应用程序中预先填充的带有标题的照片。

Example code

示例代码

Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");      

intent.putExtra(Intent.EXTRA_TEXT, "eample");
intent.putExtra(Intent.EXTRA_TITLE, "example");
intent.putExtra(Intent.EXTRA_SUBJECT, "example");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);

Intent openInChooser = new Intent(intent);
openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
startActivity(openInChooser);

Here is screen shot what I get

这是我得到的屏幕截图

Text is not display

文字不显示

If a set type to image/* then a photo is uploaded without the text prefilled. If a set it to text/plain photo is not display.....

如果将类型设置为 image/* 则上传的照片没有预填充文本。如果将其设置为文本/普通照片不显示.....

采纳答案by Eduardo Oliveira

The newest Facebook versions doesn't allow you to share text using intents. You have to use the Facebook SDK to do it - to make that simple, use the Facebook SDK + Android Simple Facebook (https://github.com/sromku/android-simple-facebook). Using the library, your code would be like this (extracted from the Simple Facebook site):

最新的 Facebook 版本不允许您使用意图共享文本。您必须使用 Facebook SDK 来做到这一点 - 为简单起见,请使用 Facebook SDK + Android Simple Facebook ( https://github.com/sromku/android-simple-facebook)。使用该库,您的代码将如下所示(摘自 Simple Facebook 站点):

Publish feed

发布提要

Set OnPublishListenerand call for:

设置OnPublishListener并调用:

  • publish(Feed, OnPublishListener)without dialog.
  • publish(Feed, true, OnPublishListener)with dialog.
  • publish(Feed, OnPublishListener)没有对话。
  • publish(Feed, true, OnPublishListener)与对话框。

Basic properties

基本属性

  • message- The message of the user
  • name- The name of the link attachment
  • caption- The caption of the link (appears beneath the link name)
  • description- The description of the link (appears beneath the link caption)
  • picture- The URL of a picture attached to this post. The picture must be at least 200px by 200px
  • link- The link attached to this post
  • message- 用户的消息
  • name- 链接附件的名称
  • caption- 链接标题(出现在链接名称下方)
  • description- 链接描述(出现在链接标题下方)
  • picture- 附加到此帖子的图片的 URL。图片必须至少为 200 像素 x 200 像素
  • link- 附加到这篇文章的链接

Initialize callback listener:

初始化回调监听器:

OnPublishListener onPublishListener = new OnPublishListener() {
    @Override
        public void onComplete(String postId) {
            Log.i(TAG, "Published successfully. The new post id = " + postId);
        }

     /* 
      * You can override other methods here: 
      * onThinking(), onFail(String reason), onException(Throwable throwable)
      */
};

Build feed:

构建提要:

Feed feed = new Feed.Builder()
    .setMessage("Clone it out...")
    .setName("Simple Facebook for Android")
    .setCaption("Code less, do the same.")
    .setDescription("The Simple Facebook library project makes the life much easier by coding less code for being able to login, publish feeds and open graph stories, invite friends and more.")
    .setPicture("https://raw.github.com/sromku/android-simple-facebook/master/Refs/android_facebook_sdk_logo.png")
    .setLink("https://github.com/sromku/android-simple-facebook")
    .build();

Publish feed withoutdialog:

发布没有对话框的提要:

mSimpleFacebook.publish(feed, onPublishListener);

Publish feed withdialog:

使用对话框发布提要:

mSimpleFacebook.publish(feed, true, onPublishListener);



Update on 14 December 2015

2015 年 12 月 14 日更新


according to New Facebook SDK.


根据新的 Facebook SDK。

facebook-android-sdk:4.6.0

facebook-android-sdk:4.6.0

It's very Simple.
1. create Provider in Android.manifest.xml

这很简单。
1.在里面创建ProviderAndroid.manifest.xml

<provider
            android:authorities="com.facebook.app.FacebookContentProvider{APP_ID}"
            android:name="com.facebook.FacebookContentProvider"
            android:exported="true" />

2. Create Your Share Intent with Data.

2. 用数据创建你的分享意图。

ShareHashtag shareHashTag = new ShareHashtag.Builder().setHashtag("#YOUR_HASHTAG").build();
ShareLinkContent shareLinkContent = new ShareLinkContent.Builder()
                .setShareHashtag(shareHashTag)
                .setQuote("Your Description")
                .setContentUrl(Uri.parse("image or logo [if playstore or app store url then no need of this image url]"))
                .build();


3. Show The Share Dialog


3. 显示共享对话框

ShareDialog.show(ShowNavigationActivity.this,shareLinkContent);


That's It.


就是这样。

回答by Baker

As of 2017, facebook doesn't allow sharing of an image + text together, directly from your app.

截至 2017 年,Facebook 不允许直接从您的应用共享图像 + 文本。

Workaround

解决方法

Facebook will though, scrape a URL for title and image data and will use that in a share post.

不过,Facebook 会抓取标题和图像数据的 URL,并将其用于分享帖子。

As a workaround you could create a single page application* that dynamically loads the text/image you want to share (specified in the URL) and you can facebook-share that URL.

作为一种解决方法,您可以创建一个单页应用程序*,动态加载您想要共享的文本/图像(在 URL 中指定),并且您可以通过 Facebook 共享该 URL。

Notes:

笔记:

  • Ensure your single page application produces a static page which has its title, open graph meta tags, and images set prior to facebook's page scrape. If these web page tags are changed dynamically through Javascript, facebook will not be able to scrape those values and use them in its share post.
  • Use open graph meta property tags og:image:height and og:image:width to allow facebook to create an image previewwithin its share post
  • 确保您的单页应用程序生成一个静态页面,该页面具有其标题、开放图形元标记和在 facebook 页面抓取之前设置的图像。如果这些网页标签通过 Javascript 动态更改,facebook 将无法抓取这些值并在其共享帖子中使用它们。
  • 使用开放图元属性标签 og:image:height 和 og:image:width 允许facebook在其共享帖子中创建图像预览

Steps

脚步

0) add the latest facebook-sdk libraryto your build.gradle file

0) 将最新的 facebook-sdk 库添加到您的 build.gradle 文件中

compile group: 'com.facebook.android', name: 'facebook-android-sdk', version: '4.25.0'

1) In your AndroidManifest.xml, add a meta-data tag within your <application>section:

1) 在您的 AndroidManifest.xml 中,在您的<application>部分中添加一个元数据标记:

<application android:label="@string/app_name" ...>
...
    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
...
</application>

Add a facebook_app_id string (with your APP ID) to your strings.xml file:

将 facebook_app_id 字符串(带有您的 APP ID)添加到您的 strings.xml 文件中:

<string name="facebook_app_id">12341234</string>

YOURFBAPPID is your Facebook App ID number found at https://developers.facebook.com/apps/

YOURFBAPPID 是您在https://developers.facebook.com/apps/ 上找到的 Facebook 应用 ID 号

2) also add a <provider>tag outside of your <application>tag in AndroidManifest.xml

2)在 AndroidManifest.xml 中的<provider>标签之外添加一个标签<application>

<provider android:authorities="com.facebook.app.FacebookContentProviderYOURFBAPPID"
          android:name="com.facebook.FacebookContentProvider"
          android:exported="true"/>

3) Create a ShareLinkContent object using their builder:

3)使用他们的构建器创建一个 ShareLinkContent 对象:

ShareLinkContent fbShare = new ShareLinkContent.Builder()
            .setContentUrl(Uri.parse("http://yourdomain.com/your-title-here/someimagefilename"))
            .build();

4) Share it from your fragment (or activity, etc.):

4)从您的片段(或活动等)中分享:

ShareDialog.show(getActivity(), fbShare);


Facebook Docs

Facebook 文档

https://developers.facebook.com/docs/android/getting-started

https://developers.facebook.com/docs/android/getting-started

回答by Vaiden

FB no longer allows you to prefill the sharing message.

FB 不再允许您预填充共享消息。

In order to circumvent this, you will need to use an SDK to publish via a Graph request. For this you will need the publish_actionspermission. Since last month you need to submit your app to a review processto gain access to publish_actions. Which you would fail if your app prefills the sharing texts. Trust me - I've had the Chutzppah to try.

为了避免这种情况,您需要使用 SDK 通过 Graph 请求进行发布。为此,您需要获得publish_actions许可。从上个月开始,您需要将您的应用提交到审核流程才能访问publish_actions. 如果您的应用预填充共享文本,您将失败。相信我 - 我已经尝试过 Chutzppah。

So it looks like we would have to comply.

所以看起来我们必须遵守。

B.t.w. in iOS you can still prefill the texts using the FB sdk. Who knows for how long.

顺便说一句,在 iOS 中,您仍然可以使用 FB sdk 预填充文本。谁知道多久。

回答by DEVSHK

In this Formula you can share image both Messenger and Instagram(com.instagram.android) without using any Provider in "AndroidManifest

在此公式中,您可以共享 Messenger 和 Instagram(com.instagram.android) 图像,而无需使用“AndroidManifest

public void shareMessenger(View v) {
    // showToast("checking");

    File dir = new File(Environment.getExternalStorageDirectory(), "MyFolder");

    File imgFile = new File(dir, "Image.png");

    Intent sendIntent = new Intent(Intent.ACTION_VIEW);
    sendIntent.setType("image/*");
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + imgFile));
    sendIntent.putExtra(Intent.EXTRA_TEXT, "<---MY TEXT--->.");
    sendIntent.setPackage("com.facebook.orca");
    sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    try {
        startActivity(Intent.createChooser(sendIntent, "Share images..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(SaveAndShareActivity.this, "Please Install Facebook Messenger", Toast.LENGTH_LONG).show();
    }

}

**Add this two line in onCreate Method **

**在onCreate方法中添加这两行**

 StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());

回答by Karthik P B

Add these lines to your following code

将这些行添加到您的以下代码中

shareCaptionIntent.putExtra(Intent.EXTRA_TITLE, "my awesome caption in the EXTRA_TITLE field");

回答by Deepshikha Puri

Without using Facebook sdk we can't share the image and text simultaneously on facebook. To solve this problem I had create a bitmap of image and text, Share that bitmap on facebook and it's working perfectly.

如果不使用 Facebook sdk,我们就无法在 facebook 上同时共享图像和文本。为了解决这个问题,我创建了一个图像和文本的位图,在 facebook 上共享该位图,它运行良好。

You can download the source code from here (Share image and text on facebook using intent in android)

您可以从这里下载源代码(在 android 中使用 Intent 在 facebook 上共享图像和文本

Here is code:

这是代码:

MainActivity.java

主活动.java

package com.shareimage;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements 
View.OnClickListener {
EditText et_text;
ImageView iv_image;
TextView tv_share,tv_text;
RelativeLayout rl_main;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    init();

}

private void init(){
    et_text = (EditText)findViewById(R.id.et_text);
    iv_image = (ImageView)findViewById(R.id.iv_image);
    tv_share = (TextView)findViewById(R.id.tv_share);
    rl_main = (RelativeLayout)findViewById(R.id.rl_main);
    tv_text= (TextView) findViewById(R.id.tv_text);

    File dir = new File("/sdcard/Testing/");
    try {
        if (dir.mkdir()) {
            System.out.println("Directory created");
        } else {
            System.out.println("Directory is not created");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    tv_share.setOnClickListener(this);

    et_text.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            tv_text.setText(et_text.getText().toString());

        }
    });


}




@Override
public void onClick(View v) {

    switch (v.getId()){
        case R.id.tv_share:
            Bitmap bitmap1 = loadBitmapFromView(rl_main, rl_main.getWidth(), rl_main.getHeight());
            saveBitmap(bitmap1);
            String str_screenshot = "/sdcard/Testing/"+"testing" + ".jpg";

            fn_share(str_screenshot);
            break;
    }

}

public void saveBitmap(Bitmap bitmap) {
    File imagePath = new File("/sdcard/Testing/"+"testing" + ".jpg");
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagePath);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();

        Log.e("ImageSave", "Saveimage");
    } catch (FileNotFoundException e) {
        Log.e("GREC", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("GREC", e.getMessage(), e);
    }
}

public static Bitmap loadBitmapFromView(View v, int width, int height) {
    Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    v.draw(c);

    return b;
}

public void fn_share(String path) {

    File file = new File("/mnt/" + path);

    Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());
    Uri uri = Uri.fromFile(file);
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_STREAM, uri);

    startActivity(Intent.createChooser(intent, "Share Image"));


}

}

回答by Vaishali Sutariya

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);

   shareIntent.setType("image/*");

   shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, (String) v.getTag(R.string.app_name));

   shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri); // put your image URI

   PackageManager pm = v.getContext().getPackageManager();

   List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);

     for (final ResolveInfo app : activityList) 
     {
         if ((app.activityInfo.name).contains("facebook")) 
         {

           final ActivityInfo activity = app.activityInfo;

           final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);

          shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);

          shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

          shareIntent.setComponent(name);

          v.getContext().startActivity(shareIntent);

          break;
        }
      }