安卓新浪微博分享实例代码

文章来源(石基技术网):http://www.58shiji.com/html/javaym/20150318/2941.html

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2.         protected void onCreate(Bundle savedInstanceState) {  
  3.                  super.onCreate(savedInstanceState);  
  4.                  setContentView(R.layout.user_center);  
  5.                  // 创建微博实例  
  6.                 mWeiboAuth = new WeiboAuth(this, Constants.APP_KEY,  
  7.                                  Constants.REDIRECT_URL, Constants.SCOPE);  
  8.                  // 创建微博分享接口实例  
  9.                 mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, Constants.APP_KEY);  
  10.     
  11.                  // 当 Activity 被重新初始化时(该 Activity 处于后台时,可能会由于内存不足被杀掉了),  
  12.                 // 需要调用 {@link IWeiboShareAPI#handleWeiboResponse} 来接收微博客户端返回的数据。  
  13.                 // 执行成功,返回 true,并调用 {@link IWeiboHandler.Response#onResponse};  
  14.                 // 失败返回 false,不调用上述回调  
  15.                 if (savedInstanceState != null) {  
  16.                          mWeiboShareAPI.handleWeiboResponse(getIntent(), this);  
  17.                  }  
  18.         }  
  19.     
  20.  /** 
  21.           * 检查用户是否安装新浪微博 
  22.          */  
  23.          public void isNotInstall() {  
  24.                  try {  
  25.                          // 检查微博客户端环境是否正常,如果未安装微博,弹出对话框询问用户下载微博客户端  
  26.                         if (mWeiboShareAPI.checkEnvironment(true)) {  
  27.     
  28.                                  // 注册第三方应用 到微博客户端中,注册成功后该应用将显示在微博的应用列表中。  
  29.                                 // 但该附件栏集成分享权限需要合作申请,详情请查看 Demo 提示  
  30.                                 mWeiboShareAPI.registerApp();  
  31.                                 startSinaShare();  
  32.                          }  
  33.                  } catch (WeiboShareException e) {  
  34.                          e.printStackTrace();  
  35.                          Toast.makeText(UserCenter.this, e.getMessage(), Toast.LENGTH_LONG)  
  36.                                          .show();  
  37.                  }  
  38.                  if (dialog != null) {  
  39.                          dialog.dismiss();  
  40.                  }  
  41.          }  
  42.     
  43.          /** 
  44.           * 微博认证授权回调类。 1. SSO 授权时,需要在 {@link #onActivityResult} 中调用 
  45.          * {@link SsoHandler#authorizeCallBack} 后, 该回调才会被执行。 2. 非 SSO 
  46.           * 授权时,当授权结束后,该回调就会被执行。 当授权成功后,请保存该 access_token、expires_in、uid 等信息到 
  47.          * SharedPreferences 中。 
  48.          */  
  49.          class AuthListener implements WeiboAuthListener {  
  50.     
  51.                  @Override  
  52.                  public void onComplete(Bundle values) {  
  53.                          // 从 Bundle 中解析 Token  
  54.                          mAccessToken = Oauth2AccessToken.parseAccessToken(values);  
  55.                          if (mAccessToken.isSessionValid()) {  
  56.                                  // 保存 Token 到 SharedPreferences  
  57.                                  AccessTokenKeeper.writeAccessToken(UserCenter.this,  
  58.                                                  mAccessToken);  
  59.                                  sendMessage();  
  60.                          }  
  61.                  }  
  62.     
  63.                  @Override  
  64.                  public void onCancel() {  
  65.                  }  
  66.     
  67.                  @Override  
  68.                  public void onWeiboException(WeiboException e) {  
  69.                          Toast.makeText(UserCenter.this,  
  70.                                          "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)  
  71.                                          .show();  
  72.                  }  
  73.          }  
  74.     
  75.          /** 
  76.           * 新浪微博用户授权 
  77.          */  
  78.          public void startSinaShare() {  
  79.                  mSsoHandler = new SsoHandler(UserCenter.this, mWeiboAuth);  
  80.     
  81.                  // 从 SharedPreferences 中读取上次已保存好 AccessToken 等信息,  
  82.                 mAccessToken = AccessTokenKeeper.readAccessToken(this);  
  83.     
  84.                  // 如果Token有效,则直接调用发送微博  
  85.                 if (mAccessToken.isSessionValid()) {  
  86.                          sendMessage();  
  87.                  } else {  
  88.                          mSsoHandler.authorize(new AuthListener());  
  89.                  }  
  90.          }  
  91.     
  92.          /** 
  93.           * @See {@link Activity#onNewIntent} 
  94.           */  
  95.          @Override  
  96.          protected void onNewIntent(Intent intent) {  
  97.                  super.onNewIntent(intent);  
  98.     
  99.                  // 从当前应用唤起微博并进行分享后,返回到当前应用时,需要在此处调用该函数  
  100.                 // 来接收微博客户端返回的数据;执行成功,返回 true,并调用  
  101.                 // {@link IWeiboHandler.Response#onResponse};失败返回 false,不调用上述回调  
  102.                 mWeiboShareAPI.handleWeiboResponse(intent, this);  
  103.          }  
  104.     
  105.          /** 
  106.           * 当 SSO 授权 Activity 退出时,该函数被调用。 
  107.          * 
  108.           * @see {@link Activity#onActivityResult} 
  109.           */  
  110.          @Override  
  111.          protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  112.                  super.onActivityResult(requestCode, resultCode, data);  
  113.                  // SSO 授权回调  
  114.                 // 重要:发起 SSO 登陆的 Activity 必须重写 onActivityResult  
  115.                  if (mSsoHandler != null) {  
  116.                          mSsoHandler.authorizeCallBack(requestCode, resultCode, data);  
  117.                  }  
  118.          }  
  119.     
  120.          /** 
  121.           * 接收微客户端博请求的数据。 当微博客户端唤起当前应用并进行分享时,该方法被调用。 
  122.          * 
  123.           * @param baseRequest 
  124.           *            微博请求数据对象 
  125.          * @see {@link IWeiboShareAPI#handleWeiboRequest} 
  126.           */  
  127.          @Override  
  128.          public void onResponse(BaseResponse baseResp) {  
  129.                  switch (baseResp.errCode) {  
  130.                  case WBConstants.ErrorCode.ERR_OK:  
  131.                          if (PublicFun.shareCondition()) {  
  132.                                  gainBoBi();  
  133.                          } else {  
  134.                                  Toast.makeText(this, R.string.share_success, Toast.LENGTH_LONG)  
  135.                                                  .show();  
  136.                          }  
  137.                          break;  
  138.                  case WBConstants.ErrorCode.ERR_CANCEL:  
  139.                          break;  
  140.                  case WBConstants.ErrorCode.ERR_FAIL:  
  141.                          Toast.makeText(this, R.string.errcode_deny, Toast.LENGTH_LONG)  
  142.                                          .show();  
  143.                          break;  
  144.                  }  
  145.                  if (dialog != null) {  
  146.                          dialog.dismiss();  
  147.                  }  
  148.          }  
  149.     
  150.          /** 
  151.           * 第三方应用发送请求消息到微博,唤起微博分享界面。 
  152.           * @see {@link #sendMultiMessage} 或者 {@link #sendSingleMessage} 
  153.           */  
  154.          private void sendMessage() {  
  155.                  if (mWeiboShareAPI.isWeiboAppSupportAPI()) {  
  156.                          sendMultiMessage();  
  157.                  } else {  
  158.                          Toast.makeText(this, R.string.sina_share_hint, Toast.LENGTH_SHORT)  
  159.                                          .show();  
  160.                  }  
  161.          }  
  162.     
  163.          /** 
  164.           * 第三方应用发送请求消息到微博,唤起微博分享界面。 注意:当 
  165.          * {@link IWeiboShareAPI#getWeiboAppSupportAPI()} >= 10351 时,支持同时分享多条消息, 
  166.          * 
  167.           * @param hasText 
  168.           *            分享的内容是否有文本 
  169.          * @param hasImage 
  170.           *            分享的内容是否有图片 
  171.          * @param hasWebpage 
  172.           *            分享的内容是否有网页 
  173.          */  
  174.          private void sendMultiMessage() {  
  175.                  // 1. 初始化微博的分享消息  
  176.                 WeiboMultiMessage weiboMessage = new WeiboMultiMessage();  
  177.                  weiboMessage.textObject = getTextObj();  
  178.                  // 用户可以分享其它媒体资源(网页、音乐、视频、声音中的一种)  
  179.                 weiboMessage.mediaObject = getWebpageObj();  
  180.                  // 2. 初始化从第三方到微博的消息请求  
  181.                 SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();  
  182.                  // 用transaction唯一标识一个请求  
  183.                 request.transaction = String.valueOf(System.currentTimeMillis());  
  184.                  request.multiMessage = weiboMessage;  
  185.     
  186.                  // 3. 发送请求消息到微博,唤起微博分享界面  
  187.                 mWeiboShareAPI.sendRequest(request);  
  188.     
  189.                  // 记录分享日志  
  190.                 PublicFun.sendShareAppLog(UserCenter.this,  
  191.                                  getResources().getString(R.string.micro_blog));  
  192.                  if (dialog != null) {  
  193.                          dialog.dismiss();  
  194.                  }  
  195.          }  
  196.     
  197.          /** 
  198.           * 创建文本消息对象。 
  199.           * @return 文本消息对象。 
  200.          */  
  201.          private TextObject getTextObj() {  
  202.                  TextObject textObject = new TextObject();  
  203.                  textObject.text = getResources().getString(R.string.share_content);  
  204.                  return textObject;  
  205.          }  
  206.     
  207.          /** 
  208.           * 创建多媒体(网页)消息对象。 
  209.           * @return 多媒体(网页)消息对象。 
  210.          */  
  211.          private WebpageObject getWebpageObj() {  
  212.                  WebpageObject mediaObject = new WebpageObject();  
  213.                  mediaObject.actionUrl = getString(R.string.share_url);  
  214.                  mediaObject.identify = Utility.generateGUID();  
  215.                  mediaObject.title = getResources().getString(R.string.share_title);  
  216.                  mediaObject.description = getString(R.string.share_content);  
  217.                  Bitmap bmp = BitmapFactory.decodeResource(getResources(),  
  218.                                  R.drawable.icon);  
  219.                  mediaObject.setThumbImage(bmp);  
  220.                  return mediaObject;  
  221.          }  
  222.     
  223.     
  224. /** 
  225.  * 该类定义了微博授权时所需要的参数。 
  226.  * @author SINA 
  227.  * @SINCE 2013-10-07 
  228.  */  
  229.  public class AccessTokenKeeper {  
  230.      private static final String PREFERENCES_NAME = "com_weibo_sdk_android";  
  231.     
  232.      private static final String KEY_UID           = "uid";  
  233.      private static final String KEY_ACCESS_TOKEN  = "access_token";  
  234.      private static final String KEY_EXPIRES_IN    = "expires_in";  
  235.     
  236.      /** 
  237.       * 保存 Token 对象到 SharedPreferences。 
  238.      * 
  239.       * @param context 应用程序上下文环境 
  240.      * @param token   Token 对象 
  241.      */  
  242.      public static void writeAccessToken(Context context, Oauth2AccessToken token) {  
  243.          if (null == context || null == token) {  
  244.              return;  
  245.          }  
  246.          SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);  
  247.          Editor editor = pref.edit();  
  248.          editor.putString(KEY_UID, token.getUid());  
  249.          editor.putString(KEY_ACCESS_TOKEN, token.getToken());  
  250.          editor.putLong(KEY_EXPIRES_IN, token.getExpiresTime());  
  251.          editor.commit();  
  252.     
  253.      }  
  254.     
  255.      /** 
  256.       * 从 SharedPreferences 读取 Token 信息。 
  257.      * 
  258.       * @param context 应用程序上下文环境 
  259.      * 
  260.       * @return 返回 Token 对象 
  261.      */  
  262.      public static Oauth2AccessToken readAccessToken(Context context) {  
  263.          if (null == context) {  
  264.              return null;  
  265.          }  
  266.     
  267.          Oauth2AccessToken token = new Oauth2AccessToken();  
  268.          SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);  
  269.          token.setUid(pref.getString(KEY_UID, ""));  
  270.          token.setToken(pref.getString(KEY_ACCESS_TOKEN, ""));  
  271.          token.setExpiresTime(pref.getLong(KEY_EXPIRES_IN, 0));  
  272.     
  273.          return token;  
  274.      }  
  275.     
  276.      /** 
  277.       * 清空 SharedPreferences 中 Token信息。 
  278.      * 
  279.       * @param context 应用程序上下文环境 
  280.      */  
  281.      public static void clear(Context context) {  
  282.          if (null == context) {  
  283.              return;  
  284.          }  
  285.          SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);  
  286.          Editor editor = pref.edit();  
  287.          editor.clear();  
  288.          editor.commit();  
  289.      }  
  290.  }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值