由于公司要接入微信分享,需求是接入纯图片分享和网页分享。这里给大家分享一下是怎么接入的。
首先在微信开发者平台注册应用
https://open.weixin.qq.com/cgi-bin/frame?t=home/app_tmpl&lang=zh_CN
微信sdk下载
https://open.weixin.qq.com/cgi-bin/showdocument? action=dir_list&t=resource/res_list&verify=1&id=open1419319167&token=&lang=zh_CN
把下载到的压缩包解压,把libs里面的jar复制到项目中
在manifest配置联网和读取sd卡权限
public void onResp(BaseResp resp) {
System.out.println("resp.errCode="+resp.errCode);
switch (resp.errCode) {
case BaseResp.ErrCode.ERR_OK:
//分享成功
Toast.makeText(this, "分享成功", Toast.LENGTH_SHORT).show();
finish();
wxApi.registerApp(Constants.APP_ID);
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
//分享取消 Toast.makeText(this, "分享取消", Toast.LENGTH_SHORT).show(); finish();
break; case BaseResp.ErrCode.ERR_AUTH_DENIED:
//分享拒绝 Toast.makeText(this, "分享拒绝", Toast.LENGTH_SHORT).show(); finish();
break;
}
}
private IWXAPI wxApi= WXAPIFactory.createWXAPI(context, Constants.APP_ID);
private static final int THUMB_SIZE = 150;
public void imageShare(String imgurl,int sendtype){
File file = new File(imgurl);
if (!file.exists()) {
Toast.makeText(context, "图片不存在", Toast.LENGTH_LONG).show();
}
WXImageObject imgObj = new WXImageObject();
imgObj.setImagePath(imgurl);
WXMediaMessage msg = new WXMediaMessage();
msg.mediaObject = imgObj;
Bitmap bmp = BitmapFactory.decodeFile(imgurl);
Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
msg.setThumbImage(thumbBmp);
bmp.recycle();
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = String.valueOf(System.currentTimeMillis());
req.message = msg;
req.scene = sendtype==0?SendMessageToWX.Req.WXSceneSession:SendMessageToWX.Req.WXSceneTimeline;
wxApi.sendReq(req);
}
public void webShare(String weburl,String imgurl,String title,String description,int sendtype){
WXWebpageObject webpage = new WXWebpageObject();
webpage.webpageUrl = weburl;
WXMediaMessage msg = new WXMediaMessage(webpage);
msg.title =title;
msg.description =description ;
Bitmap bmp = BitmapFactory.decodeFile(imgurl);
Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
msg.setThumbImage(thumbBmp);
bmp.recycle();
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("webpage");
req.message = msg;
req.scene = sendtype==0?SendMessageToWX.Req.WXSceneSession:SendMessageToWX.Req.WXSceneTimeline;
wxApi.sendReq(req);
}
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}