集成微信第三正登陆和享受功能

运微信提供的SDK进行第三着认证登陆

1.导入该包

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

2、申明用权限

<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”/>

public class MyApplication extends Application {
public static IWXAPI mWxApi;
@Override
public void onCreate() {
super.onCreate();
registerToWX();
}
private void registerToWX() {
//第二单参数是借助你以在微信开放平台上的AppID
mWxApi = WXAPIFactory.createWXAPI(this,
MainConstant.WX.WEIXIN_APP_ID, false);
// 将该app注册及微信
mWxApi.registerApp(MainConstant.WX.WEIXIN_APP_ID);
}
}

4、请求微信授权登录

//先判断是否安装微信APP,按照微信的说教,目前倒采用达到微信登录就提供原生的记名方式,需要用户安装微信客户端才会配合使用。

if (!WXUtils.isWXAppInstalled()) {
ToastUtils.showToast(“您还免设置微信客户端”);
return;
}
//微信登录
public void wxLogin() {
SendAuth.Req req = new SendAuth.Req();
req.scope = “snsapi_userinfo”;
req.state = “diandi_wx_login”;
//像微信发送请求
MyApplication.mWxApi.sendReq(req);
}

5、创建WXEntryActivity.java来接过微信的响应事件

WXEntryActivity是一个Activity,用来收取微信的应信息。这里发出几乎单需要留意的地方

它必须于”包名.wxapi”这个包下,如:你的使用包名为:com.xx.xxx.xxx,则WXEntryActivity所当的包名必须为总体包名.wxapi。这里跟签署一样,很重点,你只要名字错了,或者包名的职位错了,都是匪克回调的,切记

创办后在AndroidManifest.xml文件被针对WXEntryActivity进行设置:

<activity
android:name=”完整包名.wxapi.WXEntryActivity”
android:configChanges=”keyboardHidden|orientation|screenSize”
android:exported=”true”
android:screenOrientation=”portrait”
android:theme=”@android:style/Theme.Translucent.NoTitleBar” />

6.代码如下所示:
public class WXEntryActivity extends Activity implements
IWXAPIEventHandler {
private static final int RETURN_MSG_TYPE_LOGIN = 1;
private static final int RETURN_MSG_TYPE_SHARE = 2;
private Context mContext;
private static final String TAG = “WXEntryActivity”;
private IWXAPI api;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = this;
    MeApplication.mWxApi.handleIntent(getIntent(), this);
}

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

// 微信发送请求到第三方应用时,会回调到该方法
@Override
public void onReq(BaseReq req) {
    switch (req.getType()) {
        case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
            goToGetMsg();
            break;
        case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
            goToShowMsg((ShowMessageFromWX.Req) req);
            break;
        default:
            break;
    }
}

private void goToGetMsg() {

}

private void goToShowMsg(ShowMessageFromWX.Req showReq) {
    WXMediaMessage wxMsg = showReq.message;
    WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;

    StringBuffer msg = new StringBuffer(); // 组织一个待显示的消息内容
    msg.append("description: ");
    msg.append(wxMsg.description);
    msg.append("\n");
    msg.append("extInfo: ");
    msg.append(obj.extInfo);
    msg.append("\n");
    msg.append("filePath: ");
    msg.append(obj.filePath);
    ToastUtil.showTextToast(mContext, "show");

// Intent intent = new Intent(this, ShowFromWXActivity.class);
// intent.putExtra(Constants.ShowMsgActivity.STitle, wxMsg.title);
// intent.putExtra(Constants.ShowMsgActivity.SMessage,
msg.toString());
// intent.putExtra(Constants.ShowMsgActivity.BAThumbData,
wxMsg.thumbData);
// startActivity(intent);
// finish();
}

// 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
@Override
public void onResp(BaseResp resp) {
    int result = 0;

// Toast.makeText(this, “baseresp.getType = ” + resp.getType(),
Toast.LENGTH_SHORT).show();

    switch (resp.errCode) {
        case BaseResp.ErrCode.ERR_OK:

            switch (resp.getType()) {
                case ConstantsAPI.COMMAND_SENDAUTH:
                    //登录回调,处理登录成功的逻辑
                    String code = ((SendAuth.Resp) resp).code.trim();
                    Log.e(TAG, "code = " + code);
                    //就在这个地方,用网络库什么的或者自己封的网络api,发请求去咯,注意是get请求

                    result = R.string.errcode_success;
                    break;
                case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
                    //分享回调,处理分享成功后的逻辑
                    ToastUtil.showTextToast(mContext, "分享成功");
                    finish();
                    break;
                default:
                    break;
            }

            break;
        case BaseResp.ErrCode.ERR_USER_CANCEL:
            result = R.string.errcode_cancel;
            break;
        case BaseResp.ErrCode.ERR_AUTH_DENIED:
            result = R.string.errcode_deny;
            break;
        case BaseResp.ErrCode.ERR_UNSUPPORT:
            result = R.string.errcode_unsupported;
            break;
        default:
            result = R.string.errcode_unknown;
            break;
    }

    Toast.makeText(this, result, Toast.LENGTH_LONG).show();
    finish();
}

如上就是要的为主代码,回调成功以后就好错过要token了,目标是将到终极个人信息,记住要而因此get请求。获取玩 token之后再度去获取登陆者的个人信息,get请求虽因故自己种面临的框架即可。就是这么简单。。。。

于是微信提供的SDK来落实分享

从http://open.weixin.qq.com下载Android相关的jar包,将libammsdk.jar加入到花色遭到,或者添加依赖compile
‘com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+’

微信分享的着力类,部分代码如下:

public class WechatShareManager {
private static final int THUMB_SIZE = 150;

public static final int WECHAT_SHARE_WAY_TEXT = 1;   //文字
public static final int WECHAT_SHARE_WAY_PICTURE = 2; //图片
public static final int WECHAT_SHARE_WAY_WEBPAGE = 3;  //链接
public static final int WECHAT_SHARE_WAY_VIDEO = 4; //视频
public static final int WECHAT_SHARE_TYPE_TALK = SendMessageToWX.Req.WXSceneSession;  //会话
public static final int WECHAT_SHARE_TYPE_FRENDS = SendMessageToWX.Req.WXSceneTimeline; //朋友圈

private static WechatShareManager mInstance;
private ShareContent mShareContentText, mShareContentPicture, mShareContentWebpag, mShareContentVideo;
private IWXAPI mWXApi;
private Context mContext;

private WechatShareManager(Context context) {
    this.mContext = context;
    //初始化数据
    //初始化微信分享代码
    initWechatShare(context);
}

/**
 * 获取WeixinShareManager实例
 * 非线程安全,请在UI线程中操作
 *
 * @return
 */
public static WechatShareManager getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new WechatShareManager(context);
    }
    return mInstance;
}

private void initWechatShare(Context context) {
    if (mWXApi == null) {
        mWXApi = WXAPIFactory.createWXAPI(context, Commons.WEIXIN_APP_ID, true);
    }
    mWXApi.registerApp(Commons.WEIXIN_APP_ID);
}

/**
 * 通过微信分享
 * 分享的方式(文本、图片、链接)
 *
 * @param shareType 分享的类型(朋友圈,会话)
 */
public void shareByWebchat(ShareContent shareContent, int shareType) {
    switch (shareContent.getShareWay()) {
        case WECHAT_SHARE_WAY_TEXT:
            shareText(shareContent, shareType);
            break;
        case WECHAT_SHARE_WAY_PICTURE:
            sharePicture(shareContent, shareType);
            break;
        case WECHAT_SHARE_WAY_WEBPAGE:
            shareWebPage(shareContent, shareType);
            break;
        case WECHAT_SHARE_WAY_VIDEO:
            shareVideo(shareContent, shareType);
            break;
    }
}

private abstract class ShareContent {
    protected abstract int getShareWay();

    protected abstract String getContent();

    protected abstract String getTitle();

    protected abstract String getURL();

    protected abstract int getPictureResource();
}

/**
 * 设置分享文字的内容
 *
 * @author chengcj1
 */
public class ShareContentText extends ShareContent {
    private String content;

    /**
     * 构造分享文字类
     * 分享的文字内容
     */
    public ShareContentText(String content) {
        this.content = content;
    }

    @Override
    protected int getShareWay() {
        return WECHAT_SHARE_WAY_TEXT;
    }

    @Override
    protected String getContent() {
        return content;
    }

    @Override
    protected String getTitle() {
        return null;
    }

    @Override
    protected String getURL() {
        return null;
    }

    @Override
    protected int getPictureResource() {
        return -1;
    }
}

/*
 * 获取文本分享对象
 */
public ShareContent getShareContentText(String content) {
    if (mShareContentText == null) {
        mShareContentText = new ShareContentText(content);
    }
    return (ShareContentText) mShareContentText;
}

/**
 * 设置分享图片的内容
 *
 * @author chengcj1
 */
public class ShareContentPicture extends ShareContent {
    private int pictureResource;

    public ShareContentPicture(int pictureResource) {
        this.pictureResource = pictureResource;
    }

    @Override
    protected int getShareWay() {
        return WECHAT_SHARE_WAY_PICTURE;
    }

    @Override
    protected int getPictureResource() {
        return pictureResource;
    }

    @Override
    protected String getContent() {
        return null;
    }

    @Override
    protected String getTitle() {
        return null;
    }

    @Override
    protected String getURL() {
        return null;
    }
}

/*
 * 获取图片分享对象
 */
public ShareContent getShareContentPicture(int pictureResource) {
    if (mShareContentPicture == null) {
        mShareContentPicture = new ShareContentPicture(pictureResource);
    }
    return (ShareContentPicture) mShareContentPicture;
}

/**
 * 设置分享链接的内容
 *
 * @author chengcj1
 */
public class ShareContentWebpage extends ShareContent {
    private String title;
    private String content;
    private String url;
    private int pictureResource;

    public ShareContentWebpage(String title, String content, String url, int pictureResource) {
        this.title = title;
        this.content = content;
        this.url = url;
        this.pictureResource = pictureResource;
    }

    @Override
    protected int getShareWay() {
        return WECHAT_SHARE_WAY_WEBPAGE;
    }

    @Override
    protected String getContent() {
        return content;
    }

    @Override
    protected String getTitle() {
        return title;
    }

    @Override
    protected String getURL() {
        return url;
    }

    @Override
    protected int getPictureResource() {
        return pictureResource;
    }
}

/*
 * 获取网页分享对象
 */
public ShareContent getShareContentWebpag(String title, String content, String url, int pictureResource) {
    if (mShareContentWebpag == null) {
        mShareContentWebpag = new ShareContentWebpage(title, content, url, pictureResource);
    }
    return (ShareContentWebpage) mShareContentWebpag;
}

/**
 * 设置分享视频的内容
 *
 * @author chengcj1
 */
public class ShareContentVideo extends ShareContent {
    private String url;

    public ShareContentVideo(String url) {
        this.url = url;
    }

    @Override
    protected int getShareWay() {
        return WECHAT_SHARE_WAY_VIDEO;
    }

    @Override
    protected String getContent() {
        return null;
    }

    @Override
    protected String getTitle() {
        return null;
    }

    @Override
    protected String getURL() {
        return url;
    }

    @Override
    protected int getPictureResource() {
        return -1;
    }
}

/*
 * 获取视频分享内容
 */
public ShareContent getShareContentVideo(String url) {
    if (mShareContentVideo == null) {
        mShareContentVideo = new ShareContentVideo(url);
    }
    return (ShareContentVideo) mShareContentVideo;
}

/*
 * 分享文字
 */
private void shareText(ShareContent shareContent, int shareType) {
    String text = shareContent.getContent();
    //初始化一个WXTextObject对象
    WXTextObject textObj = new WXTextObject();
    textObj.text = text;
    //用WXTextObject对象初始化一个WXMediaMessage对象
    WXMediaMessage msg = new WXMediaMessage();
    msg.mediaObject = textObj;
    msg.description = text;
    //构造一个Req
    SendMessageToWX.Req req = new SendMessageToWX.Req();
    //transaction字段用于唯一标识一个请求
    req.transaction = buildTransaction("textshare");
    req.message = msg;
    //发送的目标场景, 可以选择发送到会话 WXSceneSession 或者朋友圈 WXSceneTimeline。 默认发送到会话。
    req.scene = shareType;
    mWXApi.sendReq(req);
}

/*
 * 分享图片
 */
private void sharePicture(ShareContent shareContent, int shareType) {
    Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), shareContent.getPictureResource());
    WXImageObject imgObj = new WXImageObject(bitmap);

    WXMediaMessage msg = new WXMediaMessage();
    msg.mediaObject = imgObj;

    Bitmap thumbBitmap = Bitmap.createScaledBitmap(bitmap, THUMB_SIZE, THUMB_SIZE, true);
    bitmap.recycle();
    msg.thumbData = Util.bmpToByteArray(thumbBitmap, true);  //设置缩略图

    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = buildTransaction("imgshareappdata");
    req.message = msg;
    req.scene = shareType;
    mWXApi.sendReq(req);
}

/*
 * 分享链接
 */
private void shareWebPage(ShareContent shareContent, int shareType) {
    WXWebpageObject webpage = new WXWebpageObject();
    webpage.webpageUrl = shareContent.getURL();
    WXMediaMessage msg = new WXMediaMessage(webpage);
    msg.title = shareContent.getTitle();
    msg.description = shareContent.getContent();

    Bitmap thumb = BitmapFactory.decodeResource(mContext.getResources(), shareContent.getPictureResource());
    if (thumb == null) {
        Toast.makeText(mContext, "图片不能为空", Toast.LENGTH_SHORT).show();
    } else {
        msg.thumbData = Util.bmpToByteArray(thumb, true);
    }

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

// shareType= SendMessageToWX.Req.WXSceneTimeline;
// shareType= SendMessageToWX.Req.WXSceneSession;

    mWXApi.sendReq(req);
}

/*
 * 分享视频
 */
private void shareVideo(ShareContent shareContent, int shareType) {
    WXVideoObject video = new WXVideoObject();
    video.videoUrl = shareContent.getURL();

    WXMediaMessage msg = new WXMediaMessage(video);
    msg.title = shareContent.getTitle();
    msg.description = shareContent.getContent();
    Bitmap thumb = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.tou_ming_pic);

// BitmapFactory.decodeStream(new URL(video.videoUrl).openStream());
/**
*
测试过程被见面冒出这种状况,会有独家手机会并发调不起微信客户端的气象。造成这种场面的故是微信对缩略图的大大小小、title、description等参数的分寸做了限定,所以产生或是大小超过了默认的限制。
*
一般景象下缩略图超出比较广泛。Title、description都是文本,一般不见面越。
*/
Bitmap thumbBitmap = Bitmap.createScaledBitmap(thumb, THUMB_SIZE,
THUMB_SIZE, true);
thumb.recycle();
msg.thumbData = Util.bmpToByteArray(thumbBitmap, true);

    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = buildTransaction("video");
    req.message = msg;
    req.scene = shareType;
    mWXApi.sendReq(req);
}

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

}

这是一个包的功能类,下面来教大家使用,util类你或找到不之于法定的demo中里面有。

1 .概念一个管理类对象 在您如果分享的地方
private WechatShareManager mShareManager;

2从此进行 获取:
mShareManager = WechatShareManager.getInstance(mContext);

3.调据此 此行代码 即可 进行分享了;
WechatShareManager.ShareContentWebpage mshareWeb =
(WechatShareManager.ShareContentWebpage)
mShareManager.getShareContentWebpag(“我以测试”, “我实在在测试”,
“www.baidu.com”,
R.drawable.icon_face);
mShareManager.shareByWebchat(mshareWeb,
WechatShareManager.WECHAT_SHARE_TYPE_TALK);

相关文章