一、准备工作
微信开放平台注册账号 -> 微信开放平台
创建应用,按要求填写应用信息(这里注意应用包签名,用debug包签名得到的appid只能debug包使用,release同理)
通过审核后拿到appID:
二、集成
1、build.gradle文件中添加依赖
android{
...
buildTypes{
debug{
minifyEnabled false
buildConfigField "String", "WECHAT_APP_ID", '"你的微信分享appID"'
}
}
}
dependencies {
api'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
}
AndroidManifext中添加需要的权限
<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"/>
2、通过一个工具类完成注册和分享内容的处理
public class WXShareManager {
private static final String APP_ID = BuildConfig.WECHAT_APP_ID;
private static final String SHARE_IMAGE_PATH = "0";
private static final String SHARE_IMAGE_DATA = "1";
private static WXShareManager manager;
private static Context appcontext;
public IWXAPI api;
public WXShareManager(Context context) {
appcontext = context;
api = WXAPIFactory.createWXAPI(appcontext, APP_ID, true);
}
public static WXShareManager getInstance(Context context) {
if (appcontext == null || !appcontext.equals(context) || manager == null) {
appcontext = context;
manager = new WXShareManager(context);
}
return manager;
}
private class WXShareThread extends Thread {
private Object content;
private String datatype;
private boolean isTimeline; //发送到朋友圈还是微信好友;
public WXShareThread(Object content, String datatype, boolean isTimeline) {
this.content = content;
this.datatype = datatype;
this.isTimeline = isTimeline;
}
@Override
public void run() {
super.run();
if (!hasPreHandleException(content)) {
WXImageObject imgObj = null;
Bitmap thumbBmp = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
switch (datatype) {
case SHARE_IMAGE_PATH:
imgObj = new WXImageObject();
imgObj.setImagePath((String) content);
thumbBmp = Bitmap.createScaledBitmap(
BitmapFactory.decodeFile((String) content, options), 150, 150, true);
break;
case SHARE_IMAGE_DATA:
imgObj = new WXImageObject();
imgObj.imageData = (byte[]) content;
thumbBmp = Bitmap.createScaledBitmap(BitmapFactory.decodeByteArray(
(byte[]) content, 0, imgObj.imageData.length), 100, 100, true);
break;
}
sharePictureToWX(imgObj, thumbBmp, isTimeline);
}
}
}
/**
* 预先检查
*
* @param content
* @return
*/
private boolean hasPreHandleException(Object content) {
if (null == content) {//空指针异常,传过来的Object是空
Looper.prepare();
Toast.makeText(appcontext, R.string.wx_err_no_content, Toast.LENGTH_SHORT).show();
Looper.loop();
return true;
}
if (!api.isWXAppInstalled()) {//微信没有安装
Looper.prepare();
Toast.makeText(appcontext, R.string.wx_err_no_install, Toast.LENGTH_SHORT).show();
Looper.loop();
return true;
}
return false;
}
public void sharePictureToWX(Object content, String datatype, boolean isTimeline) {
new WXShareThread(content, datatype, isTimeline).start();
}
/**
* 分享图片 isTimeline 是否发送朋友圈,true为朋友圈,false为朋友圈好友
*/
public void sharePictureToWX(WXImageObject mediaObject, Bitmap thumbBmp, boolean isTimeline) {
WXMediaMessage msg = new WXMediaMessage();
if (mediaObject != null) {
msg.mediaObject = mediaObject;
} else {
return;
}
if (thumbBmp != null) {
msg.thumbData = ImageUtils.bmpToByteArray(thumbBmp, true); // 设置缩略图
}
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("imgshareappdata");
req.message = msg;
req.scene = isTimeline ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
api.sendReq(req);
}
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
/**
* 分享链接
*/
public void shareUrlToWX(boolean isTimeline, String url, Bitmap thumbBmp, 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;
msg.setThumbImage(thumbBmp);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = String.valueOf(System.currentTimeMillis());
req.message = msg;
req.scene = isTimeline ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
api.sendReq(req);
}
}
public static byte[] bmpToByteArray(Bitmap bmp, boolean needRecycle) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
if (needRecycle) {
recycleBitmap(bmp);
}
byte[] result = output.toByteArray();
try {
output.close();
} catch (Exception var5) {
var5.printStackTrace();
}
return result;
}
3、微信回调
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
private static final String TAG = "WXEntryActivity";
private IWXAPI api;
private static final String APP_ID = BuildConfig.WECHAT_APP_ID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
api = WXAPIFactory.createWXAPI(this, APP_ID, true);
api.handleIntent(getIntent(), this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
api.handleIntent(intent, this);
}
@Override
public void onReq(BaseReq baseReq) {
Log.v(TAG, "onReq: ");
finish();
}
@Override
public void onResp(BaseResp baseResp) {
switch (baseResp.errCode) {
case BaseResp.ErrCode.ERR_OK:
Toast.makeText(WXEntryActivity.this, R.string.wx_err_ok, Toast.LENGTH_LONG).show();
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
Toast.makeText(WXEntryActivity.this, R.string.wx_err_auth_denied, Toast.LENGTH_LONG).show();
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
Toast.makeText(WXEntryActivity.this, R.string.wx_err_user_cancel, Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(WXEntryActivity.this, R.string.wx_err_unkown, Toast.LENGTH_LONG).show();
break;
}
finish();
}
}
需要注意的是,WXEntryActivity只能这么命名,路径一定要在 包名/wxapi 文件夹下!