java实现的新浪微博分享代码实例

内容摘要
weibo.java
{@link IWeiboShareAPI#handleWeiboResponse} 来接收微博客户端返回的数据。

// 执行成功,返回 true,并调用 {@link IWeiboHandler.Response#onR
文章正文

weibo.java

{@link IWeiboShareAPI#handleWeiboResponse} 来接收微博客户端返回的数据。
                // 执行成功,返回 true,并调用 {@link IWeiboHandler.Response#onResponse};
                // 失败返回 false,不调用上述回调
                if (savedInstanceState != null) {
                         mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
                 }
        }
 /**
          * 检查用户是否安装新浪微博
         */
         public void isNotInstall() {
                 try {
                         // 检查微博客户端环境是否正常,如果未安装微博,弹出对话框询问用户下载微博客户端
                        if (mWeiboShareAPI.checkEnvironment(true)) {
                                 // 注册第三方应用 到微博客户端中,注册成功后该应用将显示在微博的应用列表中。
                                // 但该附件栏集成分享权限需要合作申请,详情请查看 Demo 提示
                                mWeiboShareAPI.registerApp();
                                startSinaShare();
                         }
                 } catch (WeiboShareException e) {
                         e.printStackTrace();
                         Toast.makeText(UserCenter.this, e.getMessage(), Toast.LENGTH_LONG)
                                         .show();
                 }
                 if (dialog != null) {
                         dialog.dismiss();
                 }
         }
         /**
          * 微博认证授权回调类。 1. SSO 授权时,需要在 {@link #onActivityResult} 中调用
         * {@link SsoHandler#authorizeCallBack} 后, 该回调才会被执行。 2. 非 SSO
          * 授权时,当授权结束后,该回调就会被执行。 当授权成功后,请保存该 access_token、expires_in、uid 等信息到
         * SharedPreferences 中。
         */
         class AuthListener implements WeiboAuthListener {
                 @Override
                 public void onComplete(Bundle values) {
                         // 从 Bundle 中解析 Token
                         mAccessToken = Oauth2AccessToken.parseAccessToken(values);
                         if (mAccessToken.isSessionValid()) {
                                 // 保存 Token 到 SharedPreferences
                                 AccessTokenKeeper.writeAccessToken(UserCenter.this,
                                                 mAccessToken);
                                 sendMessage();
                         }
                 }
                 @Override
                 public void onCancel() {
                 }
                 @Override
                 public void onWeiboException(WeiboException e) {
                         Toast.makeText(UserCenter.this,
                                         "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
                                         .show();
                 }
         }
         /**
          * 新浪微博用户授权
         */
         public void startSinaShare() {
                 mSsoHandler = new SsoHandler(UserCenter.this, mWeiboAuth);
                 // 从 SharedPreferences 中读取上次已保存好 AccessToken 等信息,
                mAccessToken = AccessTokenKeeper.readAccessToken(this);
                 // 如果Token有效,则直接调用发送微博
                if (mAccessToken.isSessionValid()) {
                         sendMessage();
                 } else {
                         mSsoHandler.authorize(new AuthListener());
                 }
         }
         /**
          * @See {@link Activity#onNewIntent}
          */
         @Override
         protected void onNewIntent(Intent intent) {
                 super.onNewIntent(intent);
                 // 从当前应用唤起微博并进行分享后,返回到当前应用时,需要在此处调用该函数
                // 来接收微博客户端返回的数据;执行成功,返回 true,并调用
                // {@link IWeiboHandler.Response#onResponse};失败返回 false,不调用上述回调
                mWeiboShareAPI.handleWeiboResponse(intent, this);
         }
         /**
          * 当 SSO 授权 Activity 退出时,该函数被调用。
         *
          * @see {@link Activity#onActivityResult}
          */
         @Override
         protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                 super.onActivityResult(requestCode, resultCode, data);
                 // SSO 授权回调
                // 重要:发起 SSO 登陆的 Activity 必须重写 onActivityResult
                 if (mSsoHandler != null) {
                         mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
                 }
         }
         /**
          * 接收微客户端博请求的数据。 当微博客户端唤起当前应用并进行分享时,该方法被调用。
         *
          * @param baseRequest
          *            微博请求数据对象
         * @see {@link IWeiboShareAPI#handleWeiboRequest}
          */
         @Override
         public void onResponse(BaseResponse baseResp) {
                 switch (baseResp.errCode) {
                 case WBConstants.ErrorCode.ERR_OK:
                         if (PublicFun.shareCondition()) {
                                 gainBoBi();
                         } else {
                                 Toast.makeText(this, R.string.share_success, Toast.LENGTH_LONG)
                                                 .show();
                         }
                         break;
                 case WBConstants.ErrorCode.ERR_CANCEL:
                         break;
                 case WBConstants.ErrorCode.ERR_FAIL:
                         Toast.makeText(this, R.string.errcode_deny, Toast.LENGTH_LONG)
                                         .show();
                         break;
                 }
                 if (dialog != null) {
                         dialog.dismiss();
                 }
         }
         /**
          * 第三方应用发送请求消息到微博,唤起微博分享界面。
          * @see {@link #sendMultiMessage} 或者 {@link #sendSingleMessage}
          */
         private void sendMessage() {
                 if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
                         sendMultiMessage();
                 } else {
                         Toast.makeText(this, R.string.sina_share_hint, Toast.LENGTH_SHORT)
                                         .show();
                 }
         }
         /**
          * 第三方应用发送请求消息到微博,唤起微博分享界面。 注意:当
         * {@link IWeiboShareAPI#getWeiboAppSupportAPI()} >= 10351 时,支持同时分享多条消息,
         *
          * @param hasText
          *            分享的内容是否有文本
         * @param hasImage
          *            分享的内容是否有图片
         * @param hasWebpage
          *            分享的内容是否有网页
         */
         private void sendMultiMessage() {
                 // 1. 初始化微博的分享消息
                WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
                 weiboMessage.textObject = getTextObj();
                 // 用户可以分享其它媒体资源(网页、音乐、视频、声音中的一种)
                weiboMessage.mediaObject = getWebpageObj();
                 // 2. 初始化从第三方到微博的消息请求
                SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
                 // 用transaction唯一标识一个请求
                request.transaction = String.valueOf(System.currentTimeMillis());
                 request.multiMessage = weiboMessage;
                 // 3. 发送请求消息到微博,唤起微博分享界面
                mWeiboShareAPI.sendRequest(request);
                 // 记录分享日志
                PublicFun.sendShareAppLog(UserCenter.this,
                                 getResources().getString(R.string.micro_blog));
                 if (dialog != null) {
                         dialog.dismiss();
                 }
         }
         /**
          * 创建文本消息对象。
          * @return 文本消息对象。
         */
         private TextObject getTextObj() {
                 TextObject textObject = new TextObject();
                 textObject.text = getResources().getString(R.string.share_content);
                 return textObject;
         }
         /**
          * 创建多媒体(网页)消息对象。
          * @return 多媒体(网页)消息对象。
         */
         private WebpageObject getWebpageObj() {
                 WebpageObject mediaObject = new WebpageObject();
                 mediaObject.actionUrl = getString(R.string.share_url);
                 mediaObject.identify = Utility.generateGUID();
                 mediaObject.title = getResources().getString(R.string.share_title);
                 mediaObject.description = getString(R.string.share_content);
                 Bitmap bmp = BitmapFactory.decodeResource(getResources(),
                                 R.drawable.icon);
                 mediaObject.setThumbImage(bmp);
                 return mediaObject;
         }
/**
 * 该类定义了微博授权时所需要的参数。
 * @author SINA
 * @SINCE 2013-10-07
 */
 public class AccessTokenKeeper {
     private static final String PREFERENCES_NAME = "com_weibo_sdk_android";
     private static final String KEY_UID           = "uid";
     private static final String KEY_ACCESS_TOKEN  = "access_token";
     private static final String KEY_EXPIRES_IN    = "expires_in";
     /**
      * 保存 Token 对象到 SharedPreferences。
     *
      * @param context 应用程序上下文环境
     * @param token   Token 对象
     */
     public static void writeAccessToken(Context context, Oauth2AccessToken token) {
         if (null == context || null == token) {
             return;
         }
         SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
         Editor editor = pref.edit();
         editor.putString(KEY_UID, token.getUid());
         editor.putString(KEY_ACCESS_TOKEN, token.getToken());
         editor.putLong(KEY_EXPIRES_IN, token.getExpiresTime());
         editor.commit();
     }
     /**
      * 从 SharedPreferences 读取 Token 信息。
     *
      * @param context 应用程序上下文环境
     *
      * @return 返回 Token 对象
     */
     public static Oauth2AccessToken readAccessToken(Context context) {
         if (null == context) {
             return null;
         }
         Oauth2AccessToken token = new Oauth2AccessToken();
         SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
         token.setUid(pref.getString(KEY_UID, ""));
         token.setToken(pref.getString(KEY_ACCESS_TOKEN, ""));
         token.setExpiresTime(pref.getLong(KEY_EXPIRES_IN, 0));
         return token;
     }
     /**
      * 清空 SharedPreferences 中 Token信息。
     *
      * @param context 应用程序上下文环境
     */
     public static void clear(Context context) {
         if (null == context) {
             return;
         }
         SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
         Editor editor = pref.edit();
         editor.clear();
         editor.commit();
     }
 }

以上所述就是本文的全部内容了,希望对大家熟练掌握java有所帮助。


代码注释

作者:喵哥笔记

IDC笔记

学的不仅是技术,更是梦想!