Android 应用程序中的 Google Plus 共享

2024-01-25

我从早上起就一直在尝试在 google plus 流上发布内容,但它没有发布 deeplinkid 中指定的所有内容,只有 setText() 内的内容才会发布。 这是我的代码,

  Intent shareIntent = new PlusShare.Builder(this)
                    .setText("Hello Android!")
                    .setType("image/png")
                    .setContentDeepLinkId(offrdetails_data.get(0).offerLink,
                            offrdetails_data.get(0).dealTitle, 
                            offrdetails_data.get(0).dealDescription, 
                            Uri.parse(offrdetails_data.get(0).dealImage))
                    .getIntent();
startActivityForResult(shareIntent, 0);

我找到了从 android 在 google plus 上共享的解​​决方案:-

脚步 :- 1. 通过以下命令生成 SH1 密钥:-

$keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v

2:- 在 google api 控制台上创建项目并创建客户端 ID。https://developers.google.com/+/mobile/android/getting-started https://developers.google.com/+/mobile/android/getting-started

3.从 extras 将 google play 服务库添加到项目中。如果不存在,则使用 sdk 管理器下载 google play 服务。

4.在 string.xml 中添加值 /extras/google/google_play_services/samples/plus/res/values/string.xml

5.在androidManifest.xml中添加权限

      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      <uses-permission android:name="android.permission.GET_ACCOUNTS" />
      <uses-permission android:name="android.permission.VIBRATE" />
      <uses-permission android:name="android.permission.WAKE_LOCK" />

6.在您的项目中添加以下类

    public class GooglePlusShareActivity extends Activity implements  
            View.OnClickListener,
            PlusClient.ConnectionCallbacks,
            PlusClient.OnConnectionFailedListener,
            DialogInterface.OnCancelListener {
        protected static final String TAG = "ShareActivity";

        private static final String STATE_SHARING = "state_sharing";

        private static final int DIALOG_GET_GOOGLE_PLAY_SERVICES = 1;

        private static final int REQUEST_CODE_SIGN_IN = 1;
        private static final int REQUEST_CODE_INTERACTIVE_POST = 2;
        private static final int REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES = 3;

        /** The button should say "View item" in English. */
        private static final String LABEL_VIEW_ITEM = "VIEW_ITEM";

        private EditText mEditSendText;
        private boolean mSharing;
        private PlusClient mPlusClient; 

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

        mPlusClient = new PlusClient.Builder(this, this, this)
                .setActions(MomentUtil.ACTIONS)
                .build();

        Button sendButton = (Button) findViewById(R.id.send_interactive_button);
        sendButton.setOnClickListener(this);

        mEditSendText = (EditText) findViewById(R.id.share_prefill_edit);
        mSharing = savedInstanceState != null
                && savedInstanceState.getBoolean(STATE_SHARING, false);

        int available =
          GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
          if (available != ConnectionResult.SUCCESS) {
            showDialog(DIALOG_GET_GOOGLE_PLAY_SERVICES);
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        if (id != DIALOG_GET_GOOGLE_PLAY_SERVICES) {
            return super.onCreateDialog(id);
        }

        int available =  
        GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (available == ConnectionResult.SUCCESS) {
            return null;
        }
        if (GooglePlayServicesUtil.isUserRecoverableError(available)) {
            return GooglePlayServicesUtil.getErrorDialog(
                    available, this, REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES, 
        this);
        }
        return new AlertDialog.Builder(this)
                .setMessage(R.string.plus_generic_error)
                .setCancelable(true)
                .setOnCancelListener(this)
                .create();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(STATE_SHARING, mSharing);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send_interactive_button:
                if (!mPlusClient.isConnected()) {
                    // Set sharing so that the share is started in onConnected.
                    mSharing = true;

                    if (!mPlusClient.isConnecting()) {
                        mPlusClient.connect();
                    }
                } else {
                    startActivityForResult(
                            getInteractivePostIntent(), 
                  REQUEST_CODE_INTERACTIVE_POST);
                }
        }
     }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent
    intent) {
        switch (requestCode) {
            case REQUEST_CODE_SIGN_IN:
            case REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES:
                handleResult(resultCode);
                break;

            case REQUEST_CODE_INTERACTIVE_POST:
                mSharing = false;
                if (resultCode != RESULT_OK) {
                    Log.e(TAG, "Failed to create interactive post");
                }
                break;
        }
    }

    private void handleResult(int resultCode) {
        if (resultCode == RESULT_OK) {
            // onActivityResult is called after onStart (but onStart is not
            // guaranteed to be called while signing in), so we should make
            // sure we're not already connecting before we call connect again.
            if (!mPlusClient.isConnecting() && !mPlusClient.isConnected()) {
                mPlusClient.connect();
            }
        } else {
            Log.e(TAG, "Unable to sign the user in.");
            finish();
        }
    }

    private Intent getInteractivePostIntent() {
        // Create an interactive post with the "VIEW_ITEM" label. This will
        // create an enhanced share dialog when the post is shared on Google+.
        // When the user clicks on the deep link, ParseDeepLinkActivity will
        // immediately parse the deep link, and route to the appropriate 
        resource.
        String action = "/?view=true";
        Uri callToActionUrl = 
        Uri.parse(getString(R.string.plus_example_deep_link_url) + action);
        String callToActionDeepLinkId =
        getString(R.string.plus_example_deep_link_id) + action;

        // Create an interactive post builder.
        PlusShare.Builder builder = new PlusShare.Builder(this, mPlusClient);

        // Set call-to-action metadata.
        builder.addCallToAction(LABEL_VIEW_ITEM, callToActionUrl, 
        callToActionDeepLinkId);

        // Set the target url (for desktop use).
         builder.setContentUrl(Uri.parse
                    (getString(R.string.plus_example_deep_link_url)));

        // Set the target deep-link ID (for mobile use).
        builder.setContentDeepLinkId(
        getString(R.string.plus_example_deep_link_id),
                null, null, null);

        // Set the pre-filled message.
        builder.setText(mEditSendText.getText().toString());

        return builder.getIntent();
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        if (!mSharing) {
            // The share button hasn't been clicked yet.
            return;
        }

        mSharing = false;
        startActivityForResult(getInteractivePostIntent(),
     REQUEST_CODE_INTERACTIVE_POST);
    }

    @Override
    public void onDisconnected() {
        // Do nothing.
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        if (!mSharing) {
            return;
        }

        try {
            result.startResolutionForResult(this, REQUEST_CODE_SIGN_IN);
        } catch (IntentSender.SendIntentException e) {
            // Try to connect again and get another intent to start.
            mPlusClient.connect();
        }
    }

    @Override
    public void onCancel(DialogInterface dialogInterface) {
        Log.e(TAG, "Unable to sign the user in.");
        finish();
    }
}

7.添加另一个类如下

   public class MomentUtil {

    /**
     * A mapping of moment type to target URL.
     */
    public static final HashMap<String, String> MOMENT_TYPES;

    /**
     * A list of moment target types.
     */
    public static final ArrayList<String> MOMENT_LIST;
    public static final String[] ACTIONS;
    static {
        MOMENT_TYPES = new HashMap<String, String>(9);
        MOMENT_TYPES.put("AddActivity",
                "https://developers.google.com/+/plugins/snippet/examples
        /thing");
        MOMENT_TYPES.put("BuyActivity",
                "https://developers.google.com/+/plugins/snippet/examples
        /a-book");
        MOMENT_TYPES.put("CheckInActivity",
                "https://developers.google.com/+/plugins/snippet/examples
        /place");
        MOMENT_TYPES.put("CommentActivity",
                "https://developers.google.com/+/plugins/snippet/examples/blog-
        entry");
        MOMENT_TYPES.put("CreateActivity",
                "https://developers.google.com/+/plugins/snippet/examples
       /photo");
        MOMENT_TYPES.put("ListenActivity",
                "https://developers.google.com/+/plugins/snippet/examples/song");
        MOMENT_TYPES.put("ReserveActivity",
                "https://developers.google.com/+/plugins/snippet/examples

        /restaurant");
        MOMENT_TYPES.put("ReviewActivity",
                "https://developers.google.com/+/plugins/snippet/examples
        /widget");

        MOMENT_LIST = new ArrayList<String>(MomentUtil.MOMENT_TYPES.keySet());
        Collections.sort(MOMENT_LIST);

        ACTIONS = MOMENT_TYPES.keySet().toArray(new String[0]);
        int count = ACTIONS.length;
        for (int i = 0; i < count; i++) {
            ACTIONS[i] = "http://schemas.google.com/" + ACTIONS[i];
        }
    }

    /**
     * Generates the "result" JSON object for select moments.
     *
     * @param momentType The type of the moment.
     */
    public static ItemScope getResultFor(String momentType) {
        if (momentType.equals("CommentActivity")) {
            return getCommentActivityResult();
        }
        if (momentType.equals("ReserveActivity")) {
            return getReserveActivityResult();
        }
        if (momentType.equals("ReviewActivity")) {
            return getReviewActivityResult();
        }
        return null;
    }

    /**
     * Generates the "result" JSON object for CommentActivity moment.
     */
    private static ItemScope getCommentActivityResult() {
        return new ItemScope.Builder()
            .setType("http://schema.org/Comment")
            .setUrl("https://developers.google.com/+/plugins/snippet/examples
        /blog-entry#comment-1")
            .setName("This is amazing!")
            .setText("I can't wait to use it on my site!")
            .build();
    }

    /**
     * Generates the "result" JSON object for ReserveActivity moment.
     */
    private static ItemScope getReserveActivityResult() {
        return new ItemScope.Builder()
            .setType("http://schemas.google.com/Reservation")
            .setStartDate("2012-06-28T19:00:00-08:00")
            .setAttendeeCount(3)
            .build();
    }

    /**
     * Generates the "result" JSON object for ReviewActivity moment.
     */
    private static ItemScope getReviewActivityResult() {
        ItemScope rating = new ItemScope.Builder()
            .setType("http://schema.org/Rating")
            .setRatingValue("100")
            .setBestRating("100")
            .setWorstRating("0")
            .build();

        return new ItemScope.Builder()
            .setType("http://schema.org/Review")
            .setName("A Humble Review of Widget")
            .setUrl("https://developers.google.com/+/plugins/snippet/examples
          /review")
            .setText("It is amazingly effective")
            .setReviewRating(rating)
            .build();
    }
}

8.添加share_activity.xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dip">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/share_title"
        android:paddingBottom="5dip"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <EditText
        android:id="@+id/share_prefill_edit"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:inputType=""
        android:text="@string/share_prefill_text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_marginBottom="30dip" />
    <Button
        android:id="@+id/send_interactive_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/send_interactive_button_name"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

9.导入所有包ctrl+shift+O

谢谢!!我希望它会起作用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android 应用程序中的 Google Plus 共享 的相关文章

  • ContentResolver的notifyChange方法是否也通知详细的Uri?

    在应用数据期间我使用notifyChange与Uri 假设我通知content com package my items 我还有详细的Activity显示数据来自content com package my items 1 是否通知 一般
  • Flutter 中的 AndroidManifest 中缺少默认通知通道元数据

    我在用firebase messaging 5 0 1软件包来实现推送通知 在 IOS 中一切正常 而在 Android 中 当我的移动应用程序在后台运行时 我收到通知 但它没有导航到相应的屏幕 它只是打开默认屏幕 如何实现到该特定屏幕的导
  • 如何在 ADB 连接期间禁用电池充电?

    问题描述 每次我在电脑和手机之间连接 USB 线时 电池都会自动充电 我想使用 ADB 协议 但我不想在 ADB 连接期间为电池充电 是否可以关闭此充电功能 当然 我该怎么做呢 环境 Android 操作系统 4 及更高版本的手机 我只需要
  • 使用一个 apk 安装两个应用程序

    我有 2 个应用程序 1 内容提供者 2 使用此 ContentProvider 的应用程序 我需要使用单个 apk 文件安装这 2 个应用程序 我想在 Eclipse 中同时推送这两个应用程序 如果我将另一个项目添加到一个应用程序的构建路
  • API29 上不推荐使用 setColorFilter

    我使用以下行来更改 VectorDrawable 的颜色 mydrawable getBackground setColorFilter color PorterDuff Mode SRC ATOP 这很好用 尽管它现在已被弃用 文档建议我
  • 如何在 Android TextView 中使用土耳其语字符,如“ş ç ı ö”?

    我想在 android TextView 中写入 ile 但它没有正确绘制 怎样才能使用这样的字符呢 例如 我将文本视图设置为 ile 它显示为 ile 我怎样才能解决这个问题 尝试以下方法 看看是否有帮助 source http grou
  • android中根据屏幕尺寸计算图像尺寸

    我正在尝试根据屏幕尺寸计算图像高度和宽度 我从后端获取 5 x 7 尺寸的图像 为了将像素乘以 72 进行转换 我有 360 X 504 尺寸的图像 对于 360 X 504 我的动态透明矩形区域将显示为 1 223 x 1 179 即 8
  • 位图内存不足错误

    我对这个错误有疑问 我从 URL 制作网站图标解析器 我这样做是这样的 public class GrabIconsFromWebPage public static String replaceUrl String url StringB
  • Android:如何使用后台线程?

    我开发了一个应用程序 它从互联网获取内容并相应地在设备的屏幕上显示它 该程序运行得很好 就是有点慢 加载并显示内容大约需要 3 4 秒 我想将获取内容并将其显示在后台线程中的所有代码放在一起 当程序执行这些功能时 我想显示一个进度对话框 你
  • 使用 HttpUrlConnection Android 将 base64 编码的图像发送到服务器

    我正在尝试使用 HttpUrlConnection 将 base64 编码的图像发送到服务器 我遇到的问题是大多数图像均已成功发送 但有些图像会生成 FileNotFound 异常 我的图像编码代码可以在下面找到 public static
  • Android:使 Dialog 周围的所有内容都比默认值更暗

    我有一个具有以下样式的自定义对话框 它显示了一个无边框对话框 后面的任何内容都会 稍微 变暗 我的设计师希望背后的一切都比 Android 的默认设置更暗 但不是完全黑色 有这样的设置吗 我能想到的唯一解决方法是使用全屏活动而不是对话框 只
  • Emma 不生成coverage.ec

    我设置了艾玛 它曾经对我有用 然后我们更改了源代码 现在它没有生成coverage ec根本不 它确实生成coverage em 测试临近结束时 出现错误消息 exec INSTRUMENTATION CODE 0 echo Downloa
  • android textview 有字符限制吗?

    我正在尝试在 android TextView 中输入超过 2000 3000 个字符 它不显示任何内容 任何一份指南是否对 android textview 有字符限制或什么 我在G3中做了一些小测试 我发现 如果activtiy布局中有
  • 未解决的包含:“cocos2d.h” - Cocos2dx

    当我在 Eclipse 中导入 cocos2dx android 项目时 我的头文件上收到此警告 Unresolved inclusion cocos2d h 为什么是这样 它实际上困扰着我 该项目可以正确编译并运行 但我希望这种情况消失
  • Android Root 执行 su 带参数

    我在使用参数执行 su 时遇到问题 包含空格 我的 Command java 看起来像这样 public class Command Process process public String executeCommand String c
  • Android Gradle 同步失败:无法解析配置“:classpath”的所有工件

    错误如下 Caused by org gradle api internal artifacts ivyservice DefaultLenientConfiguration ArtifactResolveException Could n
  • 在 Nougat 7.1.1 中点击应用程序快捷方式时出现应用程序未安装错误

    我在向现有应用程序添加静态应用程序快捷方式时遇到一些问题 我按照以下步骤操作https developer android com guide topics ui shortcuts html https developer android
  • 如何在Android中创建一个简洁的两栏输入表单?

    我想创建一个整洁的两列输入表单 如下所示 到目前为止我的 xml 布局代码
  • Android AdMob:addView 在返回活动之前不会显示广告

    我正在尝试在游戏顶部添加横幅广告 我的活动使用带有自定义 SurfaceView 的relativelayout 我希望广告与 SurfaceView 重叠 广告会加载并可点击 但不会绘制到屏幕上 当我离开活动并返回时 会绘制广告 例如 通
  • 使用 DataBindingComponent 的 Inflate 方法

    当 Glide 成功渲染图像后 我在更新文本视图时看到此错误 致命异常 java lang IllegalStateException 必需 CustomBinding 类中的 DataBindingComponent 为 null 绑定适

随机推荐