dependencies {
compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
}
或者:
dependencies {
compile 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
}
然后添加必要的权限支持:
将自己在微信开放平台上注册之后拿到的APP_ID进行注册:
public class AppRegister extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final IWXAPI api = WXAPIFactory.createWXAPI(context, null); // 将该app注册到微信
api.registerApp(WXShare.APP_ID);
}
}
创建OnResponseListener接口:
public interface OnResponseListener {
//分享成功的回调
void onSuccess();
//分享取消的回调
void onCancel();
//分享失败的回调
void onFail(String message);
}
再继续创建WXShare类,因为我只做了分享文字和链接,在下边我会给大家补上一个分享图片的方法。
public class WXShare {
//这个APP_ID是我个人的,可以供大家使用
public static final String APP_ID = "wx10e48798def4a607";
public static final String ACTION_SHARE_RESPONSE = "action_wx_share_response";
public static final String EXTRA_RESULT = "result";
private final Context context;
private final IWXAPI api;
private OnResponseListener listener;
private ResponseReceiver receiver;
public WXShare(Context context) {
api = WXAPIFactory.createWXAPI(context, APP_ID);
this.context = context;
}
public WXShare register() {
// 微信分享
api.registerApp(APP_ID);
receiver = new ResponseReceiver();
IntentFilter filter = new IntentFilter(ACTION_SHARE_RESPONSE);
context.registerReceiver(receiver, filter);
return this;
}
public void unregister() {
try {
api.unregisterApp();
context.unregisterReceiver(receiver);
} catch (Exception e) {
e.printStackTrace();
}
}
public WXShare share(String text) {
WXTextObject textObj = new WXTextObject();
textObj.text = text;
WXMediaMessage msg = new WXMediaMessage();
msg.mediaObject = textObj;
// msg.title = "Will be ignored";
msg.description = text;
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("text");
req.message = msg;
req.scene = SendMessageToWX.Req.WXSceneSession;
boolean result = api.sendReq(req);
Log.e("text shared: " + result,"");
return this;
}
//flag用来判断是分享到微信好友还是分享到微信朋友圈,
//0代表分享到微信好友,1代表分享到朋友圈
public WXShare shareUrl(int flag,Context context,String url,String title,String descroption){
//初始化一个WXWebpageObject填写url
WXWebpageObject webpageObject = new WXWebpageObject();
webpageObject.webpageUrl = url;
//用WXWebpageObject对象初始化一个WXMediaMessage,天下标题,描述
WXMediaMessage msg = new WXMediaMessage(webpageObject);
msg.title = title;
msg.description = descroption;
//这块需要注意,图片的像素千万不要太大,不然的话会调不起来微信分享,
//我在做的时候和我们这的UIMM说随便给我一张图,她给了我一张1024*1024的图片
//当时也不知道什么原因,后来在我的机智之下换了一张像素小一点的图片好了!
Bitmap thumb = BitmapFactory.decodeResource(context.getResources(), R.mipmap.dadaoicon);
msg.setThumbImage(thumb);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = String.valueOf(System.currentTimeMillis());
req.message = msg;
req.scene = flag==0?SendMessageToWX.Req.WXSceneSession:SendMessageToWX.Req.WXSceneTimeline;
api.sendReq(req);
return this;
}
public IWXAPI getApi() {
return api;
}
public void setListener(OnResponseListener listener) {
this.listener = listener;
}
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
private class ResponseReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Response response = intent.getParcelableExtra(EXTRA_RESULT);
Log.e("type: " + response.getType(),"type: " + response.getType());
Log.e("errCode: " + response.errCode,"errCode: " + response.errCode);
String result;
if (listener != null) {
if (response.errCode == BaseResp.ErrCode.ERR_OK) {
listener.onSuccess();
} else if (response.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) {
listener.onCancel();
} else {
switch (response.errCode) {
case BaseResp.ErrCode.ERR_AUTH_DENIED:
result = "发送被拒绝";
break;
case BaseResp.ErrCode.ERR_UNSUPPORT:
result = "不支持错误";
break;
default:
result = "发送返回";
break;
}
listener.onFail(result);
}
}
}
}
public static class Response extends BaseResp implements Parcelable {
public int errCode;
public String errStr;
public String transaction;
public String openId;
private int type;
private boolean checkResult;
public Response(BaseResp baseResp) {
errCode = baseResp.errCode;
errStr = baseResp.errStr;
transaction = baseResp.transaction;
openId = baseResp.openId;
type = baseResp.getType();
checkResult = baseResp.checkArgs();
}
@Override
public int getType() {
return type;
}
@Override
public boolean checkArgs() {
return checkResult;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.errCode);
dest.writeString(this.errStr);
dest.writeString(this.transaction);
dest.writeString(this.openId);
dest.writeInt(this.type);
dest.writeByte(this.checkResult ? (byte) 1 : (byte) 0);
}
protected Response(Parcel in) {
this.errCode = in.readInt();
this.errStr = in.readString();
this.transaction = in.readString();
this.openId = in.readString();
this.type = in.readInt();
this.checkResult = in.readByte() != 0;
}
public static final Creator CREATOR = new Creator() {
@Override
public Response createFromParcel(Parcel source) {
return new Response(source);
}
@Override
public Response[] newArray(int size) {
return new Response[size];
}
};
}
}
创建WXEntryActivity,用于和微信App进行交互:
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
private IWXAPI api;
private WXShare wxShare;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wxentry);
wxShare = new WXShare(this);
wxShare.setListener(new OnResponseListener() {
@Override
public void onSuccess() {
}
@Override
public void onCancel() {
}
@Override
public void onFail(String message) {
}
});
Log.e("WXEntryActivity","WXEntryActivity");
WXShare share = new WXShare(this);
api = share.getApi();
// wxShare.share("这是要分享的文字");
wxShare.shareUrl(0,this,"https://open.weixin.qq.com","微信分享","I am so crazy","https://avatar.csdn.net/2/C/8/1_small_and_smallworld.jpg");
//注意:
// 第三方开发者如果使用透明界面来实现WXEntryActivity,
// 需要判断handleIntent的返回值,如果返回值为false,
// 则说明入参不合法未被SDK处理,应finish当前透明界面,避
// 免外部通过传递非法参数的Intent导致停留在透明界面,
// 引起用户的疑惑
try {
if (!api.handleIntent(getIntent(), this)) {
finish();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onStart() {
super.onStart();
wxShare.register();
}
@Override
protected void onDestroy() {
wxShare.unregister();
super.onDestroy();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.e("onNewIntent","onNewIntent");
setIntent(intent);
if (!api.handleIntent(intent, this)) {
finish();
}
}
@Override
public void onReq(BaseReq baseReq) {
}
@Override
public void onResp(BaseResp baseResp) {
Intent intent = new Intent(WXShare.ACTION_SHARE_RESPONSE);
intent.putExtra(WXShare.EXTRA_RESULT, new WXShare.Response(baseResp));
sendBroadcast(intent); finish();
}
}
在MainActivity中点击分享的按钮,直接跳到WXEntryActivity就好了。
就下来补加一个分享图片时用到的方法:
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);
}
接下来看一下效果图:
心得
通过这次集成微信分享发现自己阅读别人代码的能力确实还是不够,以后决定在github上多看一些开源的代码,提升自己阅读代码的能力,目前定的是两周看一个,这样可以为学习其他的技术点和做项目留下一些时间。
好了大体上就是这样,本人小白一枚,千万不要羡慕啊!!!
每天到地铁站,早高峰晚高峰那给你挤得那叫一个“舒服”,但是,到了换成站的时候总会看见一句话,这两个月总是能看见那句话,我也是用这句话来激励我自己的。——上天总是会眷顾那些一直默默学习的人
You are so crazy,why don`t you study hard???
好了,不吹牛碑了,最后附上demo的链接吧 demo下载