56net亚洲必赢社会化登录分享-微信SDK接入

来源:未知作者:编程 日期:2020/03/14 00:14 浏览:

类型地址: star 甚至 follow 感谢:)demo - gif图

转自:

本篇在依据早先封装的SocialSDK的种类上加码了WechatSDK的登入授权和分享。简介了Wechat登入分享的连片和接收注意

造个轮子吧,用本身的心迹踏实:

花色并入Wechat、QQ、天涯论坛。很烦,并不想用三方的一键分享。不及自个儿写个 sdk 吧,未来逻辑都要和煦说了算 :)

付加物概述

切切实实代码项目Github地址:https://github.com/tsy12321/SocialSDKAndroid

代码设计:
1:单一职责原则 (Single Responsibility Principle, SRP) 一个类只负责一个功能领域中的相应职责2:开闭原则 (Open-Closed Principle, OCP) 软件实体应对扩展开放,而对修改关闭3:里氏代换原则 (Liskov Substitution Principle, LSP) 所有引用基类对象的地方能够透明地使用其子类的对象4:依赖倒转原则 (Dependence Inversion Principle, DIP) 抽象不应该依赖于细节,细节应该依赖于抽象5:接口隔离原则 (Interface Segregation Principle, ISP) 使用多个专门的接口,而不使用单一的总接口6:合成复用原则 (Composite Reuse Principle, CRP) 尽量使用对象组合,而不是继承来达到复用的目的7:迪米特法则 (Law of Demeter, LoD) 一个软件实体应当尽可能少地与其他实体发生相互作用

Android U-share 6.0sdk是在5.0+的基本功上做了更加的优化,收缩了包的深浅,对于三方的jar提供了更加的多选拔(精短版,原生版),并提供了更加多实用的接口,方便了客户的三合一和升高。同临时间6.0的本子宽容5.0+的版本,老客商,只要替换对应的jar就足以了。

0 密密层层作品

系列一 Android SDK的贰遍封装和行使
系列二 源码剖析
系列三 微信SDK接入
系列四 QQ SDK接入
系列五 腾讯网和讯 SDK接入

我的 share-sdk 层次:

56net亚洲必赢 1share-sdk

专程提醒:之后大家会针对6.0+的版本提供愈来愈多方便本性的意义,所以提议客商提高,并在意大家接下去的新作用。

1 官方文书档案

Wechat的合法接入文书档案:

https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&lang=zh_CN

view层:

dialog(日常景况下的享受弹窗卡塔尔,ShareActivity(隔绝层,中间件,抽离组合两种享受回调卡塔尔国

赢得友盟Appkey

2 登入授权

Wechat的记名授权是基于OAuth2.0行业内部。

一站式的授权流程官方文档很明显:

https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419317851&token=&lang=zh_CN

那中间主要掌握多少个概念:

  1. code 调出Wechat授权明显后会重回的code,须要用那几个code去换取access_token
  2. access_token 授权成功后都是Wechat提供的接口都以透过access_token去取得的。由于access_token是code+appid+secret央求后获取的,所以建议顾客端取得到code后,该接口放在服务端进行。(这边封装的sdk secret是身处地面,调用比较有利,假诺是对安全性供给较高的提议将以此手续放到服务端进行,客户端不要贮存secret)
  3. refresh_token access_token具不经常间效果与利益性。当access_token失效后能够经过refresh_token获取一个新的access_token。但是假如refresh_token过期后,只好重复调用顾客端进行授权。
model层:

AppId(八个平台注册的appid,完成了Serializable卡塔尔ShareBean(存放分享内容,实现了Parcelable卡塔尔(قطر‎

若是你在此之前已经在友盟注册了动用,并拿走到了Appkey,能够持续使用它.

2.1 Android 接入授权代码

先开首化wxapi并注册:

this.mWXApi = WXAPIFactory.createWXAPI(context.getApplicationContext(), this.mConfig.appId);
        this.mWXApi.registerApp(this.mConfig.appId);

授权登入时调用:

SendAuth.Req req1 = new SendAuth.Req();
req1.scope = sScope;
req1.state = "snsapi_userinfo,snsapi_friend,snsapi_message";

if(!this.mWXApi.sendReq(req1)) {
    this.mAuthListener.onError(this.mConfig.getName(), "sendReq fail");
    LogUtils.e("wxapi sendReq fail");
}

回调结果:

回调解和管理理统一见前边解释。

presenter层:

透过分享类型,分享model的数码,来调起 view(ShareActivity) 进而调起 SDK (QQShare/WXShare/SineShare卡塔尔(قطر‎

一旦你从未在友盟注册开荒者账号,要求先登记,注册之后登陆你的账号,点击增添新利用,填写完应用为主音信后,将步向"下载SDK并加上代码"页面,此页面就能够取得Appkey。

3 分享

Wechat对应5种享受,2个门路(Wechat对话、交际圈)

so!依据分享的红娘类型调用Wechat区别的api。

@Override
    public void share(IShareMedia shareMedia, ShareListener shareListener) {
        this.mShareListener = shareListener;

        WXMediaMessage msg = new WXMediaMessage();
        String type = "";

        if(shareMedia instanceof ShareWebMedia) {       //网页分享
            ShareWebMedia shareWebMedia = (ShareWebMedia) shareMedia;
            type = "webpage";

            //web object
            WXWebpageObject webpageObject = new WXWebpageObject();
            webpageObject.webpageUrl = shareWebMedia.getWebPageUrl();

            msg.mediaObject = webpageObject;
            msg.title = shareWebMedia.getTitle();
            msg.description = shareWebMedia.getDescription();
            msg.thumbData = BitmapUtils.bitmap2Bytes(shareWebMedia.getThumb());
        } else if(shareMedia instanceof ShareTextMedia) {   //文字分享
            ShareTextMedia shareTextMedia = (ShareTextMedia) shareMedia;
            type = "text";

            //text object
            WXTextObject textObject = new WXTextObject();
            textObject.text = shareTextMedia.getText();

            msg.mediaObject = textObject;
            msg.description = shareTextMedia.getText();
        } else if(shareMedia instanceof ShareImageMedia) {  //图片分享
            ShareImageMedia shareImageMedia = (ShareImageMedia) shareMedia;
            type = "image";

            //image object
            WXImageObject imageObject = new WXImageObject();
            //image限制10M
            imageObject.imageData = BitmapUtils.compressBitmap(BitmapUtils.bitmap2Bytes(shareImageMedia.getImage()), 10 * 1024 * 1024);

            msg.mediaObject = imageObject;

            //直接缩放图片
            Bitmap thumb = Bitmap.createScaledBitmap(shareImageMedia.getImage(), 200, 200, true);
            msg.thumbData = BitmapUtils.bitmap2Bytes(thumb);
            thumb.recycle();
        } else if(shareMedia instanceof ShareMusicMedia) {  //音乐分享
            ShareMusicMedia shareMusicMedia = (ShareMusicMedia) shareMedia;
            type = "music";

            WXMusicObject musicObject = new WXMusicObject();
            musicObject.musicUrl = shareMusicMedia.getMusicUrl();

            msg.mediaObject = musicObject;
            msg.title = shareMusicMedia.getTitle();
            msg.description = shareMusicMedia.getDescription();
            msg.thumbData = BitmapUtils.bitmap2Bytes(shareMusicMedia.getThumb());
        } else if(shareMedia instanceof ShareVideoMedia) {      //视频分享
            ShareVideoMedia shareVideoMedia = (ShareVideoMedia) shareMedia;
            type = "video";

            WXVideoObject videoObject = new WXVideoObject();
            videoObject.videoUrl = shareVideoMedia.getVideoUrl();

            msg.mediaObject = videoObject;
            msg.title = shareVideoMedia.getTitle();
            msg.description = shareVideoMedia.getDescription();
            msg.thumbData = BitmapUtils.bitmap2Bytes(shareVideoMedia.getThumb());
        } else {
            if(this.mShareListener != null) {
                this.mShareListener.onError(this.mConfig.getName(), "shareMedia error");
            }
            return ;
        }

        //压缩缩略图到32kb
        if(msg.thumbData != null && msg.thumbData.length > '耀') {        //微信sdk里面判断的大小
            msg.thumbData = BitmapUtils.compressBitmap(msg.thumbData, '耀');
        }

        //发起request
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.message = msg;
        req.transaction = buildTransaction(type);

        if(this.mConfig.getName() == PlatformType.WEIXIN) {     //分享好友
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else if(this.mConfig.getName() == PlatformType.WEIXIN_CIRCLE) {      //分享朋友圈
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }

        if(!this.mWXApi.sendReq(req)) {
            if(this.mShareListener != null) {
                this.mShareListener.onError(this.mConfig.getName(), "sendReq fail");
            }
            LogUtils.e("wxapi sendReq fail");
        }
    }

享受中注意几点:

  1. 图表分享的图片大小在10M内
  2. 持有的缩略图要调控在32KB

然后还会有部分其余参数约束能够参见Wechatsdk能源下载下来的地点Api文书档案。

假定参数错误sendReq会重回false,不能享用。

proxy:

提供sdk入口:伊始化appid,成立分享dialog,设置点击监听 ,别的职能可依赖气象增添

下载并安装SDK

4 微信结果回调

Wechat必要类型中定死 wxapi.WXEntryActivity这么些文件,回调会调用这么些文件。所以大家自定义了叁个WXCallbackActivity,将具有剧情写在此个文件中,然后实际项目中的WXEntryActivity只须要三番五次该Activity就能够。

WXCallbackActivity见下:

public abstract class WXCallbackActivity extends Activity implements IWXAPIEventHandler {

    protected WXHandler mWXHandler = null;

    public WXCallbackActivity() {

    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SocialApi api = SocialApi.get(this.getApplicationContext());
        this.mWXHandler = (WXHandler)api.getSSOHandler(PlatformType.WEIXIN);
        this.mWXHandler.onCreate(this.getApplicationContext(), PlatformConfig.getPlatformConfig(PlatformType.WEIXIN));
        this.mWXHandler.getWXApi().handleIntent(this.getIntent(), this);
    }

    protected final void onNewIntent(Intent paramIntent) {
        super.onNewIntent(paramIntent);
        SocialApi api = SocialApi.get(this.getApplicationContext());
        this.mWXHandler = (WXHandler)api.getSSOHandler(PlatformType.WEIXIN);
        this.mWXHandler.onCreate(this.getApplicationContext(), PlatformConfig.getPlatformConfig(PlatformType.WEIXIN));
        this.mWXHandler.getWXApi().handleIntent(this.getIntent(), this);
    }

    public void onResp(BaseResp resp) {
        if(this.mWXHandler != null && resp != null) {
            try {
                this.mWXHandler.getWXEventHandler().onResp(resp);
            } catch (Exception var3) {
                ;
            }
        }

        this.finish();
    }

    public void onReq(BaseReq req) {
        if(this.mWXHandler != null) {
            this.mWXHandler.getWXEventHandler().onReq(req);
        }

        this.finish();
    }
}

在那之中发现回调的数量首倘使在onResp中拍卖,然后在WXCallbackActivity中又将最后管理放在了WXHandler中。

WXHandler的回调解和管理理:

public WXHandler() {
    this.mEventHandler = new IWXAPIEventHandler() {
        public void onResp(BaseResp resp) {
            int type = resp.getType();
            switch(type) {
                case ConstantsAPI.COMMAND_SENDAUTH:     //授权返回
                    WXHandler.this.onAuthCallback((SendAuth.Resp)resp);
                    break;

                case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:        //分享返回
                    WXHandler.this.onShareCallback((SendMessageToWX.Resp)resp);
                    break;
            }

        }

        public void onReq(BaseReq req) {
        }
    };
}

//验证回调
protected void onAuthCallback(SendAuth.Resp resp) {
    switch (resp.errCode) {
        case BaseResp.ErrCode.ERR_OK:       //授权成功
            getAuthWithCode(resp.code);
            break;

        case BaseResp.ErrCode.ERR_USER_CANCEL:      //授权取消
            if(this.mAuthListener != null) {
                this.mAuthListener.onCancel(PlatformType.WEIXIN);
            }
            break;

        default:    //授权失败
            CharSequence err = TextUtils.concat(new CharSequence[]{"weixin auth error (", String.valueOf(resp.errCode), "):", resp.errStr});
            if(mAuthListener != null) {
                mAuthListener.onError(PlatformType.WEIXIN, err.toString());
            }
            break;
    }
}

留意,在回调的一部分常量定义中(ConstantsAPI.COMMAND_SENDAUTH、BaseResp.ErrCode.ERR_OK等)都在地点的API中有定义。所以,要是反常,多看看微信提供的API文书档案。

56net亚洲必赢 2

Wechat本地API文书档案

其他:

util:缩略图的异步加载优化并展开dislrucache,连串化id等工具@IntDef声明:品质优于class和枚举,将享用门路和状态从代码里分别,解耦share:将分享作用sdk管理调用放在这里处ShareListener:将二种sdk回调在ShareActivity管理wxapi/WXEntryActivity:通过WXShare.send布罗兹cast(this, resp.errCode卡塔尔国将分享的回调发送广播传递给WXShare的播报接纳者,收到回调结果传给ShareListener(WXShare的WXShareReceiver注册在ShareActivity里卡塔尔

下载SDK最新版

结尾

上述即贯彻了Wechat平台的接入,当接入方供给连接Wechat部分时,只须要同不时候将social_sdk.jar和Wechat的sdk包同一时候引述进项目,就可以调用微信相关的报到和享受。

本篇甘休,前面还恐怕会持续接入别的平台。。。

1: Application 里

(那几个id先用美团的吧,注意替换自身的)

ShareSdkProxy.getInstance().init(this,new String[]{"214506","wxa552e31d6839de85","1550938859"});

正如图所示:

2: 自己的 Fragment 或 Acitvity 里

成立 分享视图

//创建 dialogIShareView shareDialog = ShareSdkProxy.getInstance().createShareDialog(new int[]{ShareChannel.CHANNEL_QQ, ShareChannel.CHANNEL_WEIBO, ShareChannel.CHANNEL_WECHAT_MOMENT, ShareChannel.CHANNEL_QQ_ZONE}, 4);// 设置点击回调和数据ShareSdkProxy.getInstance().setOnShareClickListener(shareDialog, getActivity(), new ShareBean("分享了", "今天天气不错", "http://118.89.233.211:3000/images/1530106897838_.jpg", R.drawable.ic_launcher, "http://www.baidu.com"));//展示 dialogshareDialog.show(getFragmentManager;

56net亚洲必赢 3

3: 自己的 Fragment 或 Acitvity 里

收到回调结果

@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { int status = data.getIntExtra(ShareActivity.RESULT_STATUS, -1); switch  { case ShareStatus.SHARE_STATUS_COMPLETE: ToastUtil.showShortToast; break; case ShareStatus.SHARE_STATUS_ERROR: ToastUtil.showShortToast; break; case ShareStatus.SHARE_STATUS_CANCEL: ToastUtil.showShortToast; break; } } }

顿时集成

1:入口ShareSdkProxy
public class ShareSdkProxy implements IShareSdkProxy { private ShareSdkProxy() { } public interface OnShareClickListener { void onShareClick(@ShareChannel int channel); } private static class Holder { private static final ShareSdkProxy IN = new ShareSdkProxy(); } public static ShareSdkProxy getInstance() { return Holder.IN; } @Override public void init(Application app, String[] appIds) { if (app != null && appIds != null && appIds.length == 3) { try { SerializeUtils.serialization(getSerializePath, new AppId(appIds[0], appIds[1], appIds[2])); } catch (Exception e) { throw new RuntimeException(" ShareSdk serialized error: " + e); } } else { throw new RuntimeException(" ShareSdk init error "); } } /** * the channel turn can inflect the turn of IShareView( in this is a dialog ) * * @param shareChannel the type of share function * @param column the column of dialog * @return the instance of dialog * @link ShareChannel.java */ @Override public IShareView createShareDialog(int[] shareChannel, int column) { return ShareDialog.get().createShareDialog(shareChannel, column); } /** * @param dialog dialog * @param activity the current activity to accept the result of the share sdk * @param shareBean the model of share function */ @Override public void setOnShareClickListener(IShareView dialog, final Activity activity, final ShareBean shareBean) { dialog.setOnShareClickListener(new OnShareClickListener() { @Override public void onShareClick(int channel) { switch  { case ShareChannel.CHANNEL_WECHAT: SharePresenter.start.onShareWx(shareBean); break; case ShareChannel.CHANNEL_WECHAT_MOMENT: SharePresenter.start.onShareWxCircle(shareBean); break; case ShareChannel.CHANNEL_QQ: SharePresenter.start.onShareQQ(shareBean); break; case ShareChannel.CHANNEL_QQ_ZONE: SharePresenter.start.onShareQZone(shareBean); break; case ShareChannel.CHANNEL_WEIBO: SharePresenter.start.onShareWeiBo(shareBean); break; case ShareChannel.CHANNEL_MORE: break; case ShareChannel.CHANNEL_CANNEL: break; } } }); }}

AndroidStudio

2:控制器:SharePresenter

控制model调起view(ShareActivity)

public class SharePresenter implements ISharePresenter { private static volatile SharePresenter presenter = null; public static ISharePresenter start(Activity activity) { if (presenter == null) { synchronized (SharePresenter.class) { if (presenter == null) presenter = new SharePresenter; } } return presenter; } private SharePresenter(Activity activity) { this.context = new WeakReference<>; } private void startActivityForResult(int type, ShareBean entry) { Activity activity = context.get(); assert activity != null : " activity weak reference maybe a null object "; activity.startActivityForResult(ShareActivity.getIntent(activity, entry, type), type); } private WeakReference<Activity> context; @Override public void onShareWeiBo(ShareBean entry) { startActivityForResult(ShareChannel.CHANNEL_WEIBO, entry); } @Override public void onShareWxCircle(ShareBean entry) { startActivityForResult(ShareChannel.CHANNEL_WECHAT_MOMENT, entry); } @Override public void onShareWx(ShareBean entry) { startActivityForResult(ShareChannel.CHANNEL_WECHAT, entry); } @Override public void onShareQQ(ShareBean entry) { startActivityForResult(ShareChannel.CHANNEL_QQ, entry); } @Override public void onShareQZone(ShareBean entry) { startActivityForResult(ShareChannel.CHANNEL_QQ_ZONE, entry); }}

1)新创设一个工程

3:隔离者,中间件:

ShareActivity,管理共享逻辑1:伊始化appid和分享type以至share的多少2:通过type 开首化 sdk3:管理sdk回调,成功、失利、废除,因Wechat分享未有提供listener,所以在wxapi下发送广播send回调response,ShareActivity注册广播选择者,选取回调新闻4:回调实现,不管怎样社团都要finish那当中间件,见finishWithResult方法

public class ShareActivity extends Activity implements WbShareCallback, ShareListener { private static final String SHARE_ENTRY = "ShareBean"; private static final String SHARE_CHANNEL = "ShareChannel"; public static final String RESULT_CHANNEL = "result_channel"; public static final String RESULT_STATUS = "result_msg"; public static Intent getIntent(Context context, ShareBean share, int type) { Intent intent = new Intent(context, ShareActivity.class); intent.putExtra(SHARE_ENTRY, share); intent.putExtra(SHARE_CHANNEL, type); return intent; } private int shareType; private WXShare wxShare; private SineShare sineShare; private QQShare qqShare; private AppId appId; private ShareBean shareBean; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_progress); Intent intent = getIntent(); shareBean = intent.getParcelableExtra(SHARE_ENTRY); shareType = intent.getIntExtra(SHARE_CHANNEL, -1); appId =  SerializeUtils.deserialization(getSerializePath(this.getApplication; switch (shareType) { case ShareChannel.CHANNEL_WECHAT: weiXinFriend(); break; case ShareChannel.CHANNEL_WECHAT_MOMENT: weiXinCircle(); break; case ShareChannel.CHANNEL_QQ: qqShare(); break; case ShareChannel.CHANNEL_QQ_ZONE: qZoneShare(); break; case ShareChannel.CHANNEL_WEIBO: weiBoShare(); break; } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent; if (sineShare != null) { sineShare.doResultIntent(intent, this); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (qqShare != null) { qqShare.onActivityResultData(requestCode, resultCode, data); } } @Override protected void onDestroy() { super.onDestroy(); if (wxShare != null) { wxShare.unregisterWXReceiver(); } } private void weiXinFriend() { wxShare = new WXShare(this, appId.getWECHAT; wxShare.registerWXReceiver(); wxShare.sendWebShareMessage(shareBean, this); } private void weiXinCircle() { wxShare = new WXShare(this, appId.getWECHAT; wxShare.registerWXReceiver(); wxShare.sendWebShareMessage(shareBean, this); } private void weiBoShare() { sineShare = new SineShare(this, appId.getWEIBO; sineShare.sendWebShareMessage(shareBean); } private void qqShare() { qqShare = new QQShare(this, appId.getQQ; qqShare.sendWebShareMessage(shareBean, this); } private void qZoneShare() { qqShare = new QQShare(this, appId.getQQ; qqShare.sendWebShareMessage(shareBean, this); } @Override public void onWbShareSuccess() { onShareSuccess(); } @Override public void onWbShareCancel() { onShareCancel(); } @Override public void onWbShareFail() { onShareFail(); } @Override public void onShareSuccess() { finishWithResult(ShareStatus.SHARE_STATUS_COMPLETE); } @Override public void onShareCancel() { finishWithResult(ShareStatus.SHARE_STATUS_CANCEL); } @Override public void onShareFail() { finishWithResult(ShareStatus.SHARE_STATUS_ERROR); } public void finishWithResult(@ShareStatus final int status) { Intent intent = new Intent(); intent.putExtra(RESULT_CHANNEL, shareType); intent.putExtra(RESULT_STATUS, status); setResult(Activity.RESULT_OK, intent); finish(); }}

56net亚洲必赢 4

4:share目录下分享sdk调用

,QQShare、WXShare、SineShare,只举一个吧WXShare:(通过flag剖断Wechat亲密的朋友仍然恋人圈)1:将 ShareBean 的多寡增进到 SDK 的调用2:管理图片3:因还没有回调的listener,提供广播

public class WXShare { private static final String ACTION_WX_CALLBACK = "com.credithc.hhr.action.WX_CALLBACK"; private static final String EXTRA_WX_RESULT = "wx_result"; private final IWXAPI iwxapi; private WXShareReceiver receiver; private Context context; private ShareListener shareListener; private boolean isTimeLine; /** * constructor for WXShare * * @param context context * @param appId 微信 id * @param flag true:好友 false:朋友圈 */ public WXShare(Context context, String appId, boolean flag) { this.context = context; iwxapi = WXAPIFactory.createWXAPI(context, appId); this.isTimeLine = flag; } /** * 注册微信回调广播 */ public void registerWXReceiver() { receiver = new WXShareReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ACTION_WX_CALLBACK); context.registerReceiver(receiver, intentFilter); } /** * unregister */ public void unregisterWXReceiver() { if (null != context && null != receiver) { context.unregisterReceiver; } } public void sendTextMessage(IShareModel shareEntry, ShareListener listener) { this.shareListener = listener; String title = shareEntry.getTitle(); String content = shareEntry.getContent(); SendMessageToWX.Req req = new SendMessageToWX.Req(); WXTextObject textObj = new WXTextObject(); textObj.text = content; WXMediaMessage msg = new WXMediaMessage(); msg.mediaObject = textObj; msg.title = title; msg.description = content; req.transaction = buildTransaction; req.message = msg; req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession; iwxapi.sendReq; } public void sendImageMessage(IShareModel shareEntry, ShareListener listener) { this.shareListener = listener; String imgUrl = shareEntry.getImgUrl(); final int drawableId = shareEntry.getDrawableId(); final WXMediaMessage msg = new WXMediaMessage(); new BitmapAsyncTask(context, imgUrl, new BitmapAsyncTask.OnBitmapListener() { @Override public void onSuccess(Bitmap bitmap) { WXImageObject imgObj = new WXImageObject; msg.mediaObject = imgObj; msg.setThumbImage(getWxShareBitmap; SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction; req.message = msg; req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession; iwxapi.sendReq; } @Override public void onException(Exception exception) { Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), drawableId); WXImageObject imgObj = new WXImageObject; Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 150, 150, true); bmp.recycle(); msg.thumbData = bmpToByteArray(thumbBmp, true); msg.mediaObject = imgObj; SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction; req.message = msg; req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession; iwxapi.sendReq; } }).execute(); } public void sendWebShareMessage(IShareModel share, ShareListener listener) { this.shareListener = listener; final String title = share.getTitle(); final String content = share.getContent(); final String imgUrl = share.getImgUrl(); final String actionUrl = share.getActionUrl(); final int drawableId = share.getDrawableId(); final SendMessageToWX.Req req = new SendMessageToWX.Req(); if (TextUtils.isEmpty { Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), drawableId); WXMediaMessage wxMediaMessage = new WXMediaMessage(); wxMediaMessage.title = title; wxMediaMessage.description = content; Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 150, 150, true); bmp.recycle(); wxMediaMessage.thumbData = bmpToByteArray(thumbBmp, true); wxMediaMessage.mediaObject = new WXWebpageObject(actionUrl); req.transaction = String.valueOf(System.currentTimeMillis; req.message = wxMediaMessage; req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession; iwxapi.sendReq; } else { new BitmapAsyncTask(context, imgUrl, new BitmapAsyncTask.OnBitmapListener() { @Override public void onSuccess(Bitmap bitmap) { WXMediaMessage wxMediaMessage = new WXMediaMessage(); wxMediaMessage.title = title; wxMediaMessage.description = content; wxMediaMessage.setThumbImage(getWxShareBitmap; wxMediaMessage.mediaObject = new WXWebpageObject(actionUrl); req.transaction = String.valueOf(System.currentTimeMillis; req.message = wxMediaMessage; req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession; iwxapi.sendReq; } @Override public void onException(Exception exception) { WXMediaMessage wxMediaMessage = new WXMediaMessage(); wxMediaMessage.title = title; wxMediaMessage.description = content; Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), drawableId); Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 150, 150, true); bmp.recycle(); wxMediaMessage.thumbData = bmpToByteArray(thumbBmp, true); wxMediaMessage.mediaObject = new WXWebpageObject(actionUrl); req.transaction = String.valueOf(System.currentTimeMillis; req.message = wxMediaMessage; req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession; iwxapi.sendReq; } }).execute(); } } public static void sendBroadcast(Context context, int errCode) { Intent intent = new Intent(); intent.setAction(ACTION_WX_CALLBACK); intent.putExtra(EXTRA_WX_RESULT, errCode); context.sendBroadcast; } /** * 微信分享回调广播 */ private class WXShareReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.hasExtra(EXTRA_WX_RESULT)) { int errCode = intent.getIntExtra(EXTRA_WX_RESULT, BaseResp.ErrCode.ERR_USER_CANCEL); Log.w("WXShareReceiver", "errCode:" + errCode); switch  { case BaseResp.ErrCode.ERR_OK: if (shareListener != null) shareListener.onShareSuccess(); break; case BaseResp.ErrCode.ERR_USER_CANCEL: if (shareListener != null) shareListener.onShareCancel(); break; default: if (shareListener != null) shareListener.onShareFail(); break; } } } } private String buildTransaction(final String type) { return (type == null) ? String.valueOf(System.currentTimeMillis : type + System.currentTimeMillis(); }}

2)拷贝jar及res

5:Dialog

1:DialogFragment2:setArguments传递参数3:recyclerview 实现 ui 展现

public class ShareDialog extends DialogFragment implements IShareView, View.OnClickListener { private TextView tvShareCancel; private RecyclerView mRecyclerView; private static final String KEY = "share_dialog_channel"; private static final String CHANNEL = "channel"; private static final String COUNT = "span_count"; private ShareSdkProxy.OnShareClickListener listener; @Override public void setOnShareClickListener(ShareSdkProxy.OnShareClickListener listener) { this.listener = listener; } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = new Dialog(getActivity(), R.style.BottomDialog); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.fragment_bottom_share); dialog.setCanceledOnTouchOutside; Window window = dialog.getWindow(); assert window != null; WindowManager.LayoutParams lp = window.getAttributes(); lp.gravity = Gravity.BOTTOM; lp.width = WindowManager.LayoutParams.MATCH_PARENT; window.setAttributes; mRecyclerView = dialog.findViewById(R.id.recycler_view_share); tvShareCancel = dialog.findViewById(R.id.tv_share_cancel); int[] arr = getArguments().getIntArray; int count = getArguments().getInt; assert arr != null; mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), count == 0 ? 4 : count)); mRecyclerView.setAdapter(new ShareAdapter; tvShareCancel.setOnClickListener; return dialog; } @Override public IShareView createShareDialog(int[] shareChannel, int spanCount) { Bundle bundle = new Bundle(); bundle.putIntArray(CHANNEL, shareChannel); bundle.putInt(COUNT, spanCount); ShareDialog dialog = new ShareDialog(); dialog.setArguments; return dialog; } @Override public int show(FragmentTransaction transaction) { return super.show(transaction, KEY); } @Override public void show(FragmentManager manager) { super.show(manager, KEY); } @Override public void onClick { dismissDialog(); } @Override public void dismissDialog() { listener.onShareClick(ShareChannel.CHANNEL_CANNEL); dismissAllowingStateLoss(); } public static IShareView get() { return new ShareDialog(); } private class ShareAdapter extends RecyclerView.Adapter<MyShareHolder> { private int[] resId; private String[] name; ShareAdapter(int[] arr) { resId = new int[arr.length]; name = new String[arr.length]; for (int i = 0; i < arr.length; i++) { if (arr[i] == ShareChannel.CHANNEL_WECHAT) { resId[i] = R.drawable.share_wx; name[i] = "微信"; } else if (arr[i] == ShareChannel.CHANNEL_WECHAT_MOMENT) { resId[i] = R.drawable.share_wx_moment; name[i] = "朋友圈"; } else if (arr[i] == ShareChannel.CHANNEL_QQ) { resId[i] = R.drawable.share_qq; name[i] = "QQ"; } else if (arr[i] == ShareChannel.CHANNEL_QQ_ZONE) { resId[i] = R.drawable.share_qq_zone; name[i] = "QQ空间"; } else if (arr[i] == ShareChannel.CHANNEL_WEIBO) { resId[i] = R.drawable.share_sine; name[i] = "微博"; } else if (arr[i] == ShareChannel.CHANNEL_MORE) { resId[i] = R.drawable.share_more; name[i] = "更多"; } else { throw new RuntimeException(" ShareChannel 数组初始化错误 "); } } } @Override public MyShareHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new MyShareHolder(LayoutInflater.from(parent.getContext.inflate(R.layout.item_share, parent, false)); } @Override public void onBindViewHolder(MyShareHolder holder, int position) { final int pos = holder.getAdapterPosition(); holder.tvName.setText(name[pos]); Drawable drawable = getContext().getResources().getDrawable(resId[pos]); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight; holder.tvName.setCompoundDrawables(null, drawable, null, null); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { switch (name[pos]) { case "微信": listener.onShareClick(ShareChannel.CHANNEL_WECHAT); break; case "朋友圈": listener.onShareClick(ShareChannel.CHANNEL_WECHAT_MOMENT); break; case "QQ": listener.onShareClick(ShareChannel.CHANNEL_QQ); break; case "QQ空间": listener.onShareClick(ShareChannel.CHANNEL_QQ_ZONE); break; case "微博": listener.onShareClick(ShareChannel.CHANNEL_WEIBO); break; case "更多": listener.onShareClick(ShareChannel.CHANNEL_MORE); break; } } }); } @Override public int getItemCount() { return resId.length; } } private static class MyShareHolder extends RecyclerView.ViewHolder { private TextView tvName; MyShareHolder(View view) { super; tvName = view.findViewById(R.id.tv_share); } }}

使用能够一贯下载下libraryapi project(':sdk-share'卡塔尔可自个儿依据实际项目ui、逻辑调度

感谢:)

a.将main文件夹以至platform(选用你想行使的阳台就能够)文件下,对应的财富文件和jar归入你的工程

举例小编想用Wechat,qq和今日头条八个平台如下图:

56net亚洲必赢 5

潜心:和讯平台有.so文件,供给在工程下树立四个jniLib的文件夹,将.so放进去,如下图所示

56net亚洲必赢 6

b.倘诺不想像a情势雷同三个个拷贝,能够运用集成工具umeng_integrate_tool.jar

56net亚洲必赢 7

双击点开这一个工具,如下图所示:

56net亚洲必赢 8

分选你想行使的阳台,以致你所使用的开垦工具,点击ok

会在当前目录下生成二个新的文本夹umeng_integratetool_result

56net亚洲必赢 9

只需将该文件夹下生成的附和文件对应放入你的工程中就可以

3卡塔尔加多对应的回调Activity

包名目录下创造wxapi文件夹,新建一个名字为WXEntryActivity的activity世襲WXCallbackActivity。这里注意早晚是包名路线下,举个例子作者的包名是com.umeng.soexample,则配备如下:

56net亚洲必赢 10

在那间您恐怕会爆红也大概不爆红那是由于IDE还一贯不sync刚才放入的jar包。

同理须要建立回调的阳台还恐怕有支付宝与易信,支付宝是索要树立三个apshare的文书夹,然后创立一个ShareEntryActivity的类,世襲ShareCallbackActivity。易信是亟需树立一个yxapi的公文夹,创建一个YXEntryActivity的类世袭YXCallbackActivity。借使不行使那四个阳台能够不要营造。

同理博客园今日头条也亟需二个回调的Activity,与Wechat分裂的是它只须要在包名目录下建设构造多少个名字为WBShareActivity类就可以,不用创立文件夹,该类世襲WBShareCallBackActivity,如下图所示(注意看目录布局):

56net亚洲必赢 11

4)修改AndroidManiFest

率先须要增添权限:

接下来步入sdk中须求的Activity:

今日头条今日头条:

android:name=".WBShareActivity"

android:configChanges="keyboardHidden|orientation"

android:screenOrientation="portrait" >

android:name="com.sina.weibo.sdk.component.WeiboSdkBrowser"

android:configChanges="keyboardHidden|orientation"

android:windowSoftInputMode="adjustResize"

android:exported="false" >

android:exported="false">

微信:

android:name=".wxapi.WXEntryActivity"

android:configChanges="keyboardHidden|orientation|screenSize"

android:exported="true"

android:screenOrientation="portrait"

android:theme="@android:style/Theme.Translucent.NoTitleBar" />

支付宝:

android:name=".apshare.ShareEntryActivity"

android:configChanges="keyboardHidden|orientation|screenSize"

android:exported="true"

android:screenOrientation="portrait"

android:theme="@android:style/Theme.Translucent.NoTitleBar" />

qq:

android:name="com.tencent.tauth.AuthActivity"

android:launchMode="singleTask"