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,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";}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
总结以上是内存溢出为你收集整理的Android 实现微信,微博,微信朋友圈,QQ分享的功能全部内容,希望文章能够帮你解决Android 实现微信,微博,微信朋友圈,QQ分享的功能所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)