【问题标题】:Google Plus sharing from android app来自 Android 应用的 Google Plus 共享
【发布时间】:2013-05-03 21:41:07
【问题描述】:

我从早上开始就一直在尝试在 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 google-plus-one google-play-services


    【解决方案1】:

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

    步骤:- 1. 通过以下命令生成 SH1 Key:-

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

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

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

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

    5.在androidMenifest.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导入所有包

    谢谢!!我希望它会工作。

    【讨论】:

    • 您的代码因“发生内部错误”而崩溃。
    • 顺便说一句,我不知道获得 CLIENT_ID 后,在代码中的何处使用它?
    • & 在 Logcat 中:“无法让用户登录。”
    • @VivekWarde,您是否按照提到的所有步骤进行操作?
    • 是的,登录成功,发布状态时存在问题!
    【解决方案2】:

    我刚刚用最小的 MainActivity 测试了你的代码,它工作正常:

    public class MainActivity extends Activity implements View.OnClickListener {
    
    private Button mButton;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        mButton = (Button) findViewById(R.id.button1);
        mButton.setOnClickListener(this);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
    public void onClick(View v) {
        Intent shareIntent = new PlusShare.Builder(this)
                .setText("Hello Android!")
                .setType("image/png")
                .setContentDeepLinkId("testID",
                        "Test Title",
                        "Test Description",
                        Uri.parse("https://developers.google.com/+/images/interactive-post-android.png"))
                .getIntent();
        startActivityForResult(shareIntent, 0);
    }
    
    }
    

    您确定offrdetails_data.get(0) 确实包含数据吗?

    针对 cme​​ts 进行编辑:可能是 offrdetails_data.get(0).offerLink 长度超过 512 个字符。

    深度链接 ID 的限制为 512 个字符(请参阅 data-calltoactiondeeplinkid 的说明):

    https://developers.google.com/+/web/share/interactive#interactive_share_button_attributes

    【讨论】:

    • 感谢李,当我将 setContentDeepLinkId() 的第一个参数更改为 testID 时,它正在工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多