Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Android 实现分享

Android 实现微信,微博,微信朋友圈,QQ分享的功能

作者:晓果博客

这篇文章主要介绍了Android 实现微信,微博,微信朋友圈,QQ分享的功能的相关资料,需要的朋友可以参考下

Android 实现微信,微博,微信朋友圈,QQ分享的功能

一、去各自所在的开发者平台注册相应的Key值;引入相关jar包、权限等

二、ShareUtil工具类

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.exception.WeiboException;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;

import java.util.List;

import cn.hnshangyu.maker.R;
import cn.hnshangyu.maker.weibo.AccessTokenKeeper;
import cn.hnshangyu.maker.weibo.Constants;

/**
 * ============================================
 * 文件名:ShareUtil.java
 * 日期:2016-08-17 14:58
 * 描述:分享帮助类
 * 版本:1.0
 * 
 * ============================================
 */
public class ShareUtil {
  /**
   * 微博微博分享接口实例
   */
  public static IWeiboShareAPI mWeiboShareAPI;
  //微信分享
  public static final String WEIXIN_SHARE_APP_ID = "wx0c********88488d";
  public static IWXAPI weixin_api;

  public static final String QQ_APP_ID = "11****5659";
  public static Tencent mTencent;

  public static void shareQQ(Activity activity, String sharePath, IUiListener listener) {
    //qq分享
    mTencent = Tencent.createInstance(QQ_APP_ID, activity);
    if (isQQClientAvailable(activity)) {

//      String content = activity.getResources().getString(R.string.ivQrcode_content);

      final Bundle params = new Bundle();
      params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
      params.putString(QQShare.SHARE_TO_QQ_TITLE, "######");
      params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "#############...");
      params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, sharePath);
//      params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "https://www.baidu.com/img/bd_logo1.png");

      mTencent.shareToQQ(activity, params, listener);
    } else {
      UIUtils.showToast(activity, "请检查是否安装最新版QQ!");
    }
  }

  /**
   * 判断qq是否可用
   *
   * @param context
   * @return
   */
  private static boolean isQQClientAvailable(Context context) {
    final PackageManager packageManager = context.getPackageManager();
    List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
    if (pinfo != null) {
      for (int i = 0; i < pinfo.size(); i++) {
        String pn = pinfo.get(i).packageName;
        if (pn.equals("com.tencent.mobileqq")) {
          return true;
        }
      }
    }
    //**如果返回false qq的轻聊版也会显示安装新版本,true他会自动下载新版本
    return true;
  }

  public static void shareWeiBo(final Activity activity, String sharePath) {
    //微博
    mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(activity, Constants.APP_KEY);

    // 1. 初始化微博的分享消息
    WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
    weiboMessage.mediaObject = getImageObj(activity);
    weiboMessage.textObject = getTextObj(activity, sharePath);

    SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
    // 用transaction唯一标识一个请求
    request.transaction = String.valueOf(System.currentTimeMillis());
    request.multiMessage = weiboMessage;

    if (mWeiboShareAPI.isWeiboAppInstalled() && mWeiboShareAPI.isWeiboAppSupportAPI()) {
      mWeiboShareAPI.registerApp();  // 将应用注册到微博客户端

      // 3. 发送请求消息到微博,唤起微博分享界面
      mWeiboShareAPI.sendRequest(activity, request);
    } else {
      AuthInfo mAuthInfo = new AuthInfo(activity, Constants.APP_KEY, Constants.REDIRECT_URL, Constants.SCOPE);

      Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(activity);
      String token = "";
      if (accessToken != null) {
        token = accessToken.getToken();
      }
      mWeiboShareAPI.sendRequest(activity, request, mAuthInfo, token, new WeiboAuthListener() {
        @Override
        public void onComplete(Bundle bundle) {
          Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
          AccessTokenKeeper.writeAccessToken(activity, newToken);

          UIUtils.showToast(activity, "onAuthorizeComplete token = " + newToken.getToken());
        }

        @Override
        public void onWeiboException(WeiboException e) {
          UIUtils.showToast(activity, "分享出错");
        }

        @Override
        public void onCancel() {
          UIUtils.showToast(activity, "分享取消");
        }
      });
    }
  }

  private static TextObject getTextObj(Activity activity, String sharePath) {
    TextObject textObject = new TextObject();
    textObject.text = "##################...@" + sharePath;
    Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher);
    textObject.setThumbImage(bitmap);
    return textObject;
  }

  /**
   * 创建图片消息对象。
   *
   * @return 图片消息对象。
   */
  private static ImageObject getImageObj(Activity activity) {
    ImageObject imageObject = new ImageObject();
//    BitmapDrawable bitmapDrawable = (BitmapDrawable) mImageView.getDrawable();
    //设置缩略图。 注意:最终压缩过的缩略图大小不得超过 32kb。
    Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher);
    imageObject.setImageObject(bitmap);
    return imageObject;
  }

  static SendMessageToWX.Req req;
  private static final int THUMB_SIZE = 150;

  public static void shareWechatCircle(Activity activity, String sharePath) {
    if (linkWeiXin(activity, sharePath)) {
      req.scene = SendMessageToWX.Req.WXSceneTimeline;
      weixin_api.sendReq(req);
    }
  }

  public static void shareWechat(Activity activity, String sharePath) {
    if (linkWeiXin(activity, sharePath)) {
      req.scene = SendMessageToWX.Req.WXSceneSession;
      weixin_api.sendReq(req);
    }
  }

  //微信分享
  private static boolean linkWeiXin(Activity activity, String sharePath) {
    // 通过WXAPIFactory工厂,获取IWXAPI的实例
    weixin_api = WXAPIFactory.createWXAPI(activity, WEIXIN_SHARE_APP_ID, true);
    if (weixin_api.isWXAppInstalled() && weixin_api.isWXAppSupportAPI()) {
      weixin_api.registerApp(WEIXIN_SHARE_APP_ID);

      WXWebpageObject webpageObject = new WXWebpageObject();
      webpageObject.webpageUrl = sharePath;

      WXMediaMessage msg = new WXMediaMessage();
      msg.mediaObject = webpageObject;
      Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher);
      msg.setThumbImage(bitmap);
      msg.title = "######";
      msg.description = "###################...";

      req = new SendMessageToWX.Req();
      req.transaction = buildTransaction("webpage");
      req.message = msg;

      return true;
    } else {
      UIUtils.showToast(activity, "请检查是否安装最新版微信!");
      return false;
    }
  }

  private static String buildTransaction(final String type) {
    return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
  }
}

三、分享界面

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;

import com.google.zxing.WriterException;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.constant.WBConstants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import butterknife.BindView;
import cn.hnshangyu.maker.R;
import cn.hnshangyu.maker.base.BaseActivity;
import cn.hnshangyu.maker.ui.personal.zxing.EncodingHandler;
import cn.hnshangyu.maker.util.ShareUtil;
import cn.hnshangyu.maker.util.UIUtils;
import cn.hnshangyu.maker.weibo.Constants;

public class InviteFriendsActivity extends BaseActivity implements IWeiboHandler.Response {

  @BindView(R.id.iv_qrcode)
  ImageView ivQrcode;
  @BindView(R.id.iv_share_qq)
  ImageView ivShareQq;
  @BindView(R.id.iv_share_weibo)
  ImageView ivShareWeibo;
  @BindView(R.id.iv_share_weixin)
  ImageView ivShareWeixin;
  @BindView(R.id.iv_share_circle_friends)
  ImageView ivShareCircleFriends;

  private Bitmap qrcodeBitmap;

  /**
   * 微博微博分享接口实例
   */
  private IWeiboShareAPI mWeiboShareAPI = null;

  //分享链接
  private String sharePath;

  @Override
  protected int getLayoutId() {
    return R.layout.activity_invite_friends;
  }

  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    // 从当前应用唤起微博并进行分享后,返回到当前应用时,需要在此处调用该函数
    // 来接收微博客户端返回的数据;执行成功,返回 true,并调用
    // {@link IWeiboHandler.Response#onResponse};失败返回 false,不调用上述回调
    mWeiboShareAPI.handleWeiboResponse(intent, this);
  }

  /**
   * 初始化控件(必须实现此方法)
   */
  @Override
  protected void initView() {
    sharePath = getResources().getString(R.string.ivQrcode_content);
    onShowTopBack(false);
    onShowTitleBack(true);
    setTitleText(R.string.invite_friends);
    showQRCode();

    // 创建微博分享接口实例
    mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, Constants.APP_KEY);

    // 注册第三方应用到微博客户端中,注册成功后该应用将显示在微博的应用列表中。
    // 但该附件栏集成分享权限需要合作申请,详情请查看 Demo 提示
    // NOTE:请务必提前注册,即界面初始化的时候或是应用程序初始化时,进行注册
    mWeiboShareAPI.registerApp();

    initListener();
  }

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // 当 Activity 被重新初始化时(该 Activity 处于后台时,可能会由于内存不足被杀掉了),
    // 需要调用 {@link IWeiboShareAPI#handleWeiboResponse} 来接收微博客户端返回的数据。
    // 执行成功,返回 true,并调用 {@link IWeiboHandler.Response#onResponse};
    // 失败返回 false,不调用上述回调
    if (savedInstanceState != null) {
      mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
    }
  }

  private void showQRCode() {
    //生成二维码图片,第一个参数是二维码的内容,第二个参数是正方形图片的边长,单位是像素
//    String content = "http://m.360buyimg.com/mobilecms/s300x98_jfs/t1363/77/1381395719/60705/ce91ad5c/55dd271aN49efd216.jpg";
//    content = getResources().getString(R.string.ivQrcode_content);
    try {
      qrcodeBitmap = EncodingHandler.createQRCode(sharePath, 400);

      ivQrcode.setImageBitmap(qrcodeBitmap);
    } catch (WriterException e) {
      e.printStackTrace();
    }

  }

  private void initListener() {
    ivShareQq.setOnClickListener(this);
    ivShareWeibo.setOnClickListener(this);
    ivShareWeixin.setOnClickListener(this);
    ivShareCircleFriends.setOnClickListener(this);
  }

  @Override
  protected void onInitClick(View v) {
    super.onInitClick(v);
    switch (v.getId()) {
      case R.id.iv_share_qq:
        ShareUtil.shareQQ(mActivity, sharePath, shareListener);
        break;
      case R.id.iv_share_weibo:
        ShareUtil.shareWeiBo(mActivity, sharePath);
        break;
      case R.id.iv_share_weixin:
        ShareUtil.shareWechat(mActivity, sharePath);
        break;
      case R.id.iv_share_circle_friends:
        ShareUtil.shareWechatCircle(mActivity, sharePath);
        break;
    }
  }

  @Override
  public void onResponse(BaseResponse baseResponse) {
    if (baseResponse != null) {
      switch (baseResponse.errCode) {
        case WBConstants.ErrorCode.ERR_OK:
          UIUtils.showToast(mContext, "分享成功");
          break;
        case WBConstants.ErrorCode.ERR_CANCEL:
          UIUtils.showToast(mContext, "分享取消");
          break;
        case WBConstants.ErrorCode.ERR_FAIL:
          UIUtils.showToast(mContext, "分享失败");
          break;
      }
    }
  }

  private IUiListener shareListener = new IUiListener() {
    @Override
    public void onComplete(Object o) {
      UIUtils.showToast(mContext, "分享成功");
    }

    @Override
    public void onError(UiError uiError) {
      UIUtils.showToast(mContext, "分享出错");
    }

    @Override
    public void onCancel() {
    }
  };

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == com.tencent.connect.common.Constants.REQUEST_QQ_SHARE) {
      Tencent.onActivityResultData(requestCode, resultCode, data, shareListener);
    }
  }
}

四、Constants类

/**
 * 该类定义了微博授权时所需要的参数。
 */
public interface Constants {

  /**
   * 当前 应用的 APP_KEY,第三方应用应该使用自己的 APP_KEY 替换该 APP_KEY
   */
  public static final String APP_KEY = "16#####007";

  /**
   * 当前 应用的回调页,第三方应用可以使用自己的回调页。
   * <p/>
   * <p>
   * 注:关于授权回调页对移动客户端应用来说对用户是不可见的,所以定义为何种形式都将不影响,
   * 但是没有定义将无法使用 SDK 认证登录。
   * 建议使用默认回调页:https://api.weibo.com/oauth2/default.html
   * </p>
   */
//  public static final String REDIRECT_URL = "http://www.sina.com";
  public static final String REDIRECT_URL = "https://api.weibo.com/oauth2/default.html";
  /**
   * Scope 是 OAuth2.0 授权机制中 authorize 接口的一个参数。通过 Scope,平台将开放更多的微博
   * 核心功能给开发者,同时也加强用户隐私保护,提升了用户体验,用户在新 OAuth2.0 授权页中有权利
   * 选择赋予应用的功能。
   * <p/>
   * 我们通过新浪微博开放平台-->管理中心-->我的应用-->接口管理处,能看到我们目前已有哪些接口的
   * 使用权限,高级权限需要进行申请。
   * <p/>
   * 目前 Scope 支持传入多个 Scope 权限,用逗号分隔。
   * <p/>
   * 有关哪些 OpenAPI 需要权限申请,请查看:http://open.weibo.com/wiki/%E5%BE%AE%E5%8D%9AAPI
   * 关于 Scope 概念及注意事项,请查看:http://open.weibo.com/wiki/Scope
   */
  public static final String SCOPE =
      "email,direct_messages_read,direct_messages_write,"
          + "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
          + "follow_app_official_microblog," + "invitation_write";
}

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

您可能感兴趣的文章:
阅读全文