最新消息:欢迎访问Android开发中文站!商务联系QQ:1304524325

Android平台快速集成当下流行平台分享

新手入门 loading 1357浏览 0评论

前言

时别两个月,处理好学校的事情,我又回来了。今天给大家带来当下流行平台的分享集成,分别是微信好友、微信朋友圈、QQ好友、QQ空间以及新浪微博的分享集成。

集成jar包

微信

微信接入指南

在app级别的build.gradle中添加如下依赖:

compile ‘com.tencent.mm.opensdk:wechat-sdk-Android-with-mta:+’

QQ

QQ接入指南

导入qq_simple.jar包即可

新浪微博

新浪微博接入指南

1.导入weiboSDKCore_3.1.4.jar包

2.导入so文件,见下图

这里写图片描述

3.在在app级别的build.gradle中添加资源设置

//这里要特别注意,不同文件夹下面的so文件都要报上一级目录包含进来
    sourceSets {
        main {
           // jniLibs.srcDirs = ['libs/share/weiboso']
            jniLibs.srcDirs('libs/share/weiboso','libs')//可变参数,可以加任意个so文件父目录,否则会抛异常
        }
    }

配置清单文件及回调Activity编码

微信

文件名称必须是wxapi,两个回调Activity必须是WXEntryActivity和WXPayEntryActivity

这里写图片描述

 <!-- 微信通用Activity -->
        <activity
            android:name=".wxapi.WXEntryActivity"
            android:exported="true"
            android:launchMode="singleTop"/>
        <!-- 微信支付 -->
        <activity
            android:name=".wxapi.WXPayEntryActivity"
            android:exported="true"
            android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:scheme="wx0e42a8f6cc530cd0"/>
            </intent-filter>
            </activity>
        <!-- end -->

QQ

 <!-- QQ -->
        <activity
            android:name="com.tencent.tauth.AuthActivity"
            android:launchMode="singleTask"
            android:noHistory="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>

                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>

                <data android:scheme="1105809896"/>
            </intent-filter>
        </activity>
        <activity
            android:name="com.tencent.connect.common.AssistActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"/>

新浪微博

新浪微博的回调Activity要实现IWeiboHandler.Response接口,来完成微博分享的回调

package com.sinosoft.nanniwan.share;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

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.auth.WeiboAuthListener;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sinosoft.nanniwan.base.BaseApplication;
import com.sinosoft.nanniwan.base.BaseAuthorityActivity;
import com.sinosoft.nanniwan.utils.Toaster;

/**
 * 创建日期:2017/6/23 8:46
 * 微博回调基类
 * @author yzz
 */
public abstract class WeiBoShareBaseActivity extends Activity implements IWeiboHandler.Response {

    protected IWeiboShareAPI mWeiboShareAPI;
    protected boolean isFirst = true;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (mWeiboShareAPI == null) return;
        mWeiboShareAPI.handleWeiboResponse(intent, this); //当前应用唤起微博分享后,返回当前应用
    }

    /**
     * 解决微博点击取消保存草稿无法正常接收到回调的bug
     */
    @Override
    protected void onResume() {
        super.onResume();
        if (mWeiboShareAPI == null) return;
        if (!isFirst) {
            boolean isResp = mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
            if (!isResp) {
                finish();
            }
        }
        isFirst = false;
    }

    @Override
    public void onResponse(BaseResponse baseResponse) {
        switch (baseResponse.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toaster.show(getApplicationContext(), "分享成功", Toast.LENGTH_SHORT);
                finish();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toaster.show(getApplicationContext(), "已取消", Toast.LENGTH_SHORT);
                finish();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toaster.show(getApplicationContext(), "分享失败", Toast.LENGTH_SHORT);
                finish();
                break;
            default:
                finish();
                break;
        }
    }
}

/**
 * 创建日期:2017/6/23 8:46
 * 微博回调实现类
 * @author yzz
 */
public class WeiBoShareActivity extends WeiBoShareBaseActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_wei_bo_share);
        if (getIntent() == null) return;

        ShareUtils.Helper helper = getIntent().getParcelableExtra("helper");
        if (helper == null) {
            finish();
            return;
        }

        //创建微博API接口类对象
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, helper.getWeiboAPPID());
        mWeiboShareAPI.registerApp();

        ShareUtils utils = new ShareUtils(helper);
        mWeiboShareAPI.sendRequest(this, utils.shareWB(this));
    }
}

分享工具类封装

package com.sinosoft.nanniwan.share;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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.sinosoft.nanniwan.R;
import com.sinosoft.nanniwan.base.BaseApplication;
import com.sinosoft.nanniwan.utils.Toaster;
import com.sinosoft.nanniwan.widget.MyPopWindow;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.util.ArrayList;

/**
 * 创建日期:2017/6/22 14:49
 *
 * @author yzz
 */
public class ShareUtils implements View.OnClickListener {
    private ViewGroup mGroup;
    private MyPopWindow mShareWindow;
    private Helper helper;
    private IWXAPI iwxapi;
    private Activity context;

    public ShareUtils(Helper helper) {
        this.helper = helper;
    }

    public void showShare(Activity context) {
        this.context = context;
        if (mShareWindow == null) mShareWindow = new MyPopWindow(context);
        if (mGroup == null)
            mGroup = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.share_item, null);
        shareClick();
        mShareWindow.addView(mGroup);
    }

    public SendMultiMessageToWeiboRequest shareWB(Activity context) {
        return weiBo(context);
    }

    /**
     * 分享的点击事件
     */
    private void shareClick() {
        View link = mGroup.findViewById(R.id.link);
        View wx = mGroup.findViewById(R.id.wx);
        View wxmoments = mGroup.findViewById(R.id.wxmoments);
        View qq = mGroup.findViewById(R.id.qq);
        View qqzoon = mGroup.findViewById(R.id.qqzoon);
        View weibo = mGroup.findViewById(R.id.weibo);
        View cacel = mGroup.findViewById(R.id.cancel);
        View cancleV = mGroup.findViewById(R.id.cancel_v);
        link.setOnClickListener(this);
        wx.setOnClickListener(this);
        wxmoments.setOnClickListener(this);
        qq.setOnClickListener(this);
        qqzoon.setOnClickListener(this);
        weibo.setOnClickListener(this);
        cacel.setOnClickListener(this);
        cancleV.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.link:
                copLink();
                break;
            case R.id.wx:
                shareWx(true);
                break;
            case R.id.wxmoments:
                shareWx(false);
                break;
            case R.id.qq:
                QQ();
                break;
            case R.id.qqzoon:
                QQZoon();
                break;
            case R.id.weibo:
                if (Util.checkIsinstalled(BaseApplication.getBaseApplication(),"com.sina.weibo")) {
                    Intent intent = new Intent(context, WeiBoShareActivity.class);
                    intent.putExtra("helper", helper);
                    context.startActivity(intent);
                }else {
                    Toaster.show(BaseApplication.getBaseApplication(),"检测到您手机未安新浪微博程序");
                }
                break;
            case R.id.cancel:
            case R.id.cancel_v:
                mShareWindow.removeView();
                break;
        }
    }

    /**
     * 复制链接
     */
    public void copLink() {

    }

    /**
     * @param isFriend 是否是分享到好友
     */
    private void shareWx(final boolean isFriend) {
        //检查是否安装了微信
        if (!Util.checkIsinstalled(BaseApplication.getBaseApplication(),"com.tencent.mm")){
            Toaster.show(BaseApplication.getBaseApplication(),"检测到您手机未安装微信程序");
            return;
        }
        WXWebpageObject webpageObject = new WXWebpageObject();
        webpageObject.webpageUrl = helper.webUrl;
        WXMediaMessage wxMediaMessage = new WXMediaMessage(webpageObject);
        wxMediaMessage.title = helper.webtitle;
        wxMediaMessage.description = helper.webDescrible;
        wxMediaMessage.thumbData = Util.compressImage(BitmapFactory.decodeResource(context.getResources(),helper.imgId));
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = Helper.buildTransaction("webpage");
        req.message = wxMediaMessage;
        req.scene = isFriend ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
        // 调用api接口发送数据到微信
        if (iwxapi == null) iwxapi = WXAPIFactory.createWXAPI(context, helper.WxAPPID);
        iwxapi.sendReq(req);
    }

    /**
     * ##QQ好友
     * QQShare.SHARE_TO_QQ_KEY_TYPE 必填  Int 分享的类型。图文分享(普通分享)填Tencent.SHARE_TO_QQ_TYPE_DEFAULT
     * QQShare.PARAM_TARGET_URL 必填  String  这条分享消息被好友点击后的跳转URL。
     * QQShare.PARAM_TITLE  必填  String  分享的标题, 最长30个字符。
     * QQShare.PARAM_SUMMARY    可选  String  分享的消息摘要,最长40个字。
     * QQShare.SHARE_TO_QQ_IMAGE_URL    可选  String  分享图片的URL或者本地路径
     * QQShare.SHARE_TO_QQ_APP_NAME 可选  String  手Q客户端顶部,替换“返回”按钮文字,如果为空,用返回代替
     * QQShare.SHARE_TO_QQ_EXT_INT  可选  Int 分享额外选项,两种类型可选(默认是不隐藏分享到QZone按钮且不自动打开分享到QZone的对话框):
     * QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN,分享时自动打开分享到QZone的对话框。
     * QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE,分享时隐藏分享到QZone按钮
     */
    private void QQ() {
        final Bundle params = new Bundle();
        Tencent mTencent = Tencent.createInstance(helper.QQAPPID, context);
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, helper.webtitle);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, helper.webDescrible);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, helper.webUrl);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, helper.imgURL);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "南泥湾");
        mTencent.shareToQQ(context, params, new IUiListener() {
            @Override
            public void onComplete(Object o) {

            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {

            }
        });
    }

    /**
     * ##QQ空间
     * QzoneShare.SHARE_TO_QQ_KEY_TYPE  选填  Int SHARE_TO_QZONE_TYPE_IMAGE_TEXT(图文)
     * QzoneShare.SHARE_TO_QQ_TITLE 必填  Int 分享的标题,最多200个字符。
     * QzoneShare.SHARE_TO_QQ_SUMMARY   选填  String  分享的摘要,最多600字符。
     * QzoneShare.SHARE_TO_QQ_TARGET_URL    必填  String  需要跳转的链接,URL字符串。
     * QzoneShare.SHARE_TO_QQ_IMAGE_URL 选填  String  分享的图片, 以ArrayList<String>的类型传入,以便支持多张图片(注:图片最多支持9张图片,多余的图片会被丢弃)。
     */
    private void QQZoon() {
        //分享类型
        Tencent mTencent = Tencent.createInstance(helper.QQAPPID, context);
        final Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, helper.webtitle);//必填
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, helper.webDescrible);//选填
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, helper.webUrl);//必填
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, helper.imgs);
        mTencent.shareToQzone(context, params, new IUiListener() {
            @Override
            public void onComplete(Object o) {

            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {

            }
        });
    }

    /**
     * 微博分享(这里的上下文不一样)WeiBoShareActivity
     */
    private SendMultiMessageToWeiboRequest weiBo(Activity context) {

        if (helper == null || helper.weiboAPPID == null || helper.webtitle == null) return null;
        // 1. 初始化微博的分享消息

        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        weiboMessage.textObject = getTextObj();
        weiboMessage.imageObject = getImageObj(context);
        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;
        return request;
    }

    /**
     * 创建文本消息对象。
     *
     * @return 文本消息对象。
     */
    private TextObject getTextObj() {
        TextObject textObject = new TextObject();
        textObject.text = helper.webDescrible;
        textObject.title = helper.webtitle;
        textObject.actionUrl = helper.webUrl;
        return textObject;
    }

    /**
     * 创建图片消息对象。
     *
     * @return 图片消息对象。
     */
    private ImageObject getImageObj(Context context) {
        ImageObject imageObject = new ImageObject();
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),helper.imgId);
        imageObject.setImageObject(bitmap);

        return imageObject;
    }

    /**
     * 数据承载类
     */
    public static class Helper implements Parcelable {
        private String webUrl;
        private String webtitle;
        private String webDescrible;
        private int imgId;
        private String WxAPPID;
        private String QQAPPID;
        //QQZoon需要
        private ArrayList<String> imgs;
        private String imgURL;
        private String weiboAPPID;

        public Helper() {

        }

        public String getWebUrl() {
            return webUrl;
        }

        public String getWebtitle() {
            return webtitle;
        }

        public String getWebDescrible() {
            return webDescrible;
        }

        public int getImgId() {
            return imgId;
        }

        public String getWxAPPID() {
            return WxAPPID;
        }

        public String getQQAPPID() {
            return QQAPPID;
        }

        public ArrayList<String> getImgs() {
            return imgs;
        }

        public String getImgURL() {
            return imgURL;
        }

        public String getWeiboAPPID() {
            return weiboAPPID;
        }

        protected Helper(Parcel in) {
            webUrl = in.readString();
            webtitle = in.readString();
            webDescrible = in.readString();
            imgId = in.readInt();
            WxAPPID = in.readString();
            QQAPPID = in.readString();
            imgs = in.createStringArrayList();
            imgURL = in.readString();
            weiboAPPID = in.readString();
        }

        public static final Creator<Helper> CREATOR = new Creator<Helper>() {
            @Override
            public Helper createFromParcel(Parcel in) {
                Helper helper = new Helper();
                helper.webUrl = in.readString();
                helper.webtitle = in.readString();
                helper.webDescrible = in.readString();
                helper.imgId = in.readInt();
                helper.WxAPPID = in.readString();
                helper.QQAPPID = in.readString();
                helper.imgs = in.createStringArrayList();
                helper.imgURL = in.readString();
                helper.weiboAPPID = in.readString();
                return helper;
            }

            @Override
            public Helper[] newArray(int size) {
                return new Helper[size];
            }
        };

        //微信转化需要
        private static String buildTransaction(final String type) {
            return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
        }

        public Helper webUrl(final String webUrl) {
            this.webUrl = webUrl;
            return this;
        }

        public Helper webtitle(final String webtitle) {
            this.webtitle = webtitle;
            return this;
        }

        public Helper webDescrible(final String webDescrible) {
            this.webDescrible = webDescrible;
            return this;
        }

        public Helper imgId(final  int imgId) {
            this.imgId = imgId;
            return this;
        }

        public Helper WxAPPID(final String WxAPPID) {
            this.WxAPPID = WxAPPID;
            return this;
        }

        public Helper QQAPPID(final String QQAPPID) {
            this.QQAPPID = QQAPPID;
            return this;
        }

        public Helper imgs(final ArrayList<String> imgs) {
            this.imgs = imgs;
            return this;
        }

        public Helper imgURL(final String imgURL) {
            this.imgURL = imgURL;
            return this;
        }

        public Helper weiboAPPID(final String weiboAPPID) {
            this.weiboAPPID = weiboAPPID;
            return this;
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(webUrl);
            dest.writeString(webtitle);
            dest.writeString(webDescrible);
            dest.writeInt(imgId);
            dest.writeString(WxAPPID);
            dest.writeString(QQAPPID);
            dest.writeStringList(imgs);
            dest.writeString(imgURL);
            dest.writeString(weiboAPPID);
        }
    }

    @Override
    public String toString() {
        return "ShareUtils{" +
                "mGroup=" + mGroup +
                ", mShareWindow=" + mShareWindow +
                ", helper=" + helper +
                ", iwxapi=" + iwxapi +
                ", context=" + context +
                '}';
    }
}

辅助工具方法

微信分享的图片不能超过32kb,需要进行图片压缩,知道满足条件才可调起微信

 /**
     * 质量压缩方法
     *
     * @param image
     * @return
     */
    public static byte[] compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        int options = 90;

        while (baos.toByteArray().length / 1024 > 32) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
            options -= 5;// 每次都减少5
        }
        byte[] bytes = baos.toByteArray();
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

调用分享工具

shareutils = new ShareUtils(new ShareUtils
                            .Helper()
                            .WxAPPID(Config.W_APPKEY)
                            .webDescrible("应用测试描述")
                            .webtitle("应用测试标题")
                            .webUrl(shareUrl)
                            .QQAPPID(Config.QQ_APPID)
                            .imgURL(shareUrl)
                            .imgId(R.drawable.app_icon)
                            .weiboAPPID(Config.WB_APPID)
                            .imgs(list)
                    ) {
                        @Override
                        public void copLink() {
                            //复制链接
                        }
                    };

总结

需要注意的是在导入so文件的时候要注意,要写到文件上级目录,系统才能去调用so文件,否则抛异常,jniLibs.srcDirs(String.calss…str)是可变参数,所以很方便,我们可以将不同的so文件分开进行配置。只要注意到这点就基本上没啥问题了。由于项目的特殊性,无法提供源码,上述基本上已经帖出了相关代码,谢谢。

转载请注明:Android开发中文站 » Android平台快速集成当下流行平台分享

您必须 登录 才能发表评论!