Android微信、微博、QQ分享,官方集成

2017-07-10  本文已影响1385人  Jsonzhang

前言

最近项目中需要分享功能,就集成官方的分享,特此记录下,便于自己后续回顾。
注意:我都是分享的网址即URL,其他分享类似

微信分享

微信开放平台:https://open.weixin.qq.com
官方文档:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419317340&token=&lang=zh_CN

dependencies {
    compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
}
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
private IWXAPI iwxapi;
iwxapi = WXAPIFactory.createWXAPI(this, GlobalConfig.WEIXIN_APP_ID);
 iwxapi.registerApp(GlobalConfig.WEIXIN_APP_ID);
// 微信分享网页
    private void shareWeb(boolean isToFriend) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = "你的网页地址url";

        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = "网页标题";
        msg.description = "网页描述";

        Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.aa);
        msg.thumbData = bmpToByteArray(thumb);

        // 构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        // transaction字段用于唯一标识一个请求
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isToFriend ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
        iwxapi.sendReq(req);
    }

    private byte[] bmpToByteArray(Bitmap bmp) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

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

此时已经可以分享成功了,测试需要用正式的包测试,不然会被微信拒绝。如果不小心用了debug办的测试了,微信可能会存在缓存,这样你即使用正式版的有可能也会被拒,这就需要你在微信中清理下数据。然后分享就ok了。
还有一点就是,我在开发过程中只想分享单一的url,所以我将msg.titlemsg.description都置为空字符串。并且将msg.thumbData也注释掉,这样就不能分享了,后来我试了几次发现这几个值都不能缺,并且有的值不能置为空串。

android:exported="true"
/**
 * 微信分享回调Activity
 */
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    private IWXAPI iwxapi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wxentry);
        iwxapi = WXAPIFactory.createWXAPI(this, GlobalConfig.WEIXIN_APP_ID, false);
        iwxapi.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        iwxapi.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
    }

    // APP请求微信响应结果回调
    @Override
    public void onResp(BaseResp baseResp) {
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                ToastUtil.showShortToast(WXEntryActivity.this, "分享成功");
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                ToastUtil.showShortToast(WXEntryActivity.this, "分享被取消");
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                ToastUtil.showShortToast(WXEntryActivity.this, "分享被拒绝");
                break;
        }
        finish(); // 注意在:如果不finishing会有一层白色的activity
    }
}

QQ和QQ空间分享

腾讯开放平台:http://open.qq.com
官方文档:http://wiki.open.qq.com/index.php?title=Android_API调用说明&=45038#1.13_.E5.88.86.E4.BA.AB.E6.B6.88.E6.81.AF.E5.88.B0QQ.EF.BC.88.E6.97.A0.E9.9C.80QQ.E7.99.BB.E5.BD.95.EF.BC.89

<uses-permission android:name="android.permission.INTERNET" />  
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

在AndroidManifest.xml 文件的application节点内加入如下内容

  <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="tencent你的appid" />
         </intent-filter>
 </activity>

  <activity     
       android:name="com.tencent.connect.common.AssistActivity"
       android:screenOrientation="portrait"
       android:theme="@android:style/Theme.Translucent.NoTitleBar" />
mTencent = Tencent.createInstance(你的APP_ID, this.getApplicationContext());
    private IUiListener mIUiListener;
    // oncreat方法中实例化mIUiListener = new MyShareListener();
    // 自定义QQ分享回调接口
    private class MyShareListener implements IUiListener {

        @Override
        public void onComplete(Object o) {
            // 分享成功
            ToastUtil.showShortToast(NewForwardDetailActivity.this, "分享成功");
        }

        @Override
        public void onError(UiError uiError) {
            // 分享错误
            ToastUtil.showShortToast(NewForwardDetailActivity.this, "分享失败");
        }

        @Override
        public void onCancel() {
            // 取消分享
            ToastUtil.showShortToast(NewForwardDetailActivity.this, "取消分享");
        }
    }

在onActivityResult中监测分享状态

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);
        if (requestCode == Constants.REQUEST_API) {
            if (resultCode == Constants.REQUEST_QQ_SHARE || resultCode == Constants.REQUEST_QZONE_SHARE || resultCode == Constants.REQUEST_OLD_SHARE) {
                Tencent.handleResultData(data, mIUiListener);
            }
        }
  }
private void shareToQQ() {
        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, shareUrl);// 内容地址
        // params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://imgcache.qq.com/qzone/space_item/pre/0/66768.gif");// 网络图片地址  
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "医师工作站");// 应用名称
        // params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "其它附加功能");
        // 分享操作要在主线程中完成
        mTencent.shareToQQ(NewForwardDetailActivity.this, params, mIUiListener);
    }

    private void shareToQQZone() {
        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, "医生工作站");//必填
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, "最新前沿文章推荐阅读");//选填
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, shareUrl);//必填
        ArrayList<String> imageUrls = new ArrayList<>();
        imageUrls.add("http://www.beehood.com/uploads/allimg/150310/2-150310142133.jpg");
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);// 必填,否则无法启动分享
        mTencent.shareToQzone(NewForwardDetailActivity.this, params, mIUiListener);
    }

注意:分享到qq空间时,我开始没有写params.putStringArrayList,所以点击分享没有反应,后来查阅资料得知,这是必填项,必须要写

微博分享

微博开放平台:http://open.weibo.com/index.php
Github资料:https://github.com/sinaweibosdk/weibo_android_sdk
官方文档:http://open.weibo.com/wiki/Android_sdk说明文档(很差)

屏幕快照 2017-07-10 下午5.27.31.png

可以看下那个4.0的文档

allprojects {
    repositories {
        jcenter()
        mavenCentral()
        maven { url "https://dl.bintray.com/thelasterstar/maven/" }
    }
}
compile 'com.sina.weibo.sdk:core:2.0.3:openDefaultRelease@aar'

将sdk中so目录下的所有文件放入到你项目中的jniLibs,如果没有自己新建,是在main目录下,与res目录同级,不要建错位置。

WbSdk.install(this, new AuthInfo(this,你的APP_KEY, GlobalConfig.REDIRECT_URL, GlobalConfig.SCOPE));
 wbShareHandler = new WbShareHandler(this);
 wbShareHandler.registerApp();
// 这两个参数固定写就可以
public static final String REDIRECT_URL = "http://www.sina.com";
 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";
}
public class NewForwardDetailActivity extends BaseActivity implements View.OnClickListener, WbShareCallback {

并实现三个回调方法:

// 微博分享回调
    @Override
    public void onWbShareSuccess() {
        ToastUtil.showShortToast(NewForwardDetailActivity.this, "分享成功");
    }
    @Override
    public void onWbShareCancel() {
        ToastUtil.showShortToast(NewForwardDetailActivity.this, "取消分享");
    }
    @Override
    public void onWbShareFail() {
        ToastUtil.showShortToast(NewForwardDetailActivity.this, "分享失败");
    }

处理分享回调


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        wbShareHandler.doResultIntent(intent, this); // 第二个参数是分享回调的接口
    }
    private void shareToWeibo(boolean hasText, boolean hasImage) {
        sendMultiMessage(hasText, hasImage);
    }
    private void sendMultiMessage(boolean hasText, boolean hasImage) {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        if (hasText) {
            weiboMessage.textObject = getTextObj();
        }
        if (hasImage) {
            weiboMessage.imageObject = getImageObj();
        }
        weiboMessage.mediaObject = getWebpageObj();
        wbShareHandler.shareMessage(weiboMessage, true);
    }
    private TextObject getTextObj() {
        TextObject textObject = new TextObject();
        textObject.text = "分享的文字";
        textObject.title = "分享的title";
        textObject.actionUrl = "http://www.baidu.com";
        return textObject;
    }
    private ImageObject getImageObj() {
        ImageObject imageObject = new ImageObject();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo2);
        imageObject.setImageObject(bitmap);
        return imageObject;
    }
    private WebpageObject getWebpageObj() {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = "#医生工作站#最新前沿相关文章推荐阅读";
        mediaObject.description = "最新前沿相关文章推荐阅读";
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.weibo_share);
        mediaObject.setThumbImage(bitmap);
        mediaObject.actionUrl = shareUrl;
        mediaObject.defaultText = "Webpage";
        return mediaObject;
    }
上一篇下一篇

猜你喜欢

热点阅读