最近在做项目中用到了微信分享的功能,项目中做了一个朋友圈的动态发布来记录宝宝的成长日记,
有一个功能是微信分享,刚开始没有头绪,后来了解了微信分享之后发现也是不难实现的一个功能。
下面就来看看微信分享的实现吧。首先来看一下如图的微信分享的实现界面:
1:这个方法是shareToWeixin()其中的参数是项目中发朋友圈写的日记
/**
* 日记的分享
*/
private void shareToWeixin(final Diary diary) {
//WinnerApplication是项目的全局类
if (!WinnerApplication.mWxApi.isWXAppInstalled()) {
Toast.makeText(context, "您还未安装微信", Toast.LENGTH_SHORT).show();
return;
}
if (!NetUtil.IsActivityNetWork(context)) {
Toast.makeText(context, "请检查您的网络连接", Toast.LENGTH_SHORT).show();
return;
}
//新加上去的//要考虑日记没有图片时候的情况
if(diary.getDiaryImg().get(0)!=null&&!diary.getDiaryImg().get(0).equals("")) {
getImage(diary.getDiaryImg().get(0), new HttpCallBackListener() {
@Override
public void onFinish(final Bitmap bitmap) {
UIUtils.runOnUIThread(new Runnable() {
@Override
public void run() {
WXWebpageObject webpage = new WXWebpageObject();
webpage.webpageUrl = APIConfig.getShareDiarysUrl(diary.getDiaryId());
final WXMediaMessage msg = new WXMediaMessage(webpage);
//新加上去的
msg.title = "快来看看宝宝的成长日记吧!";
//新加上去的
msg.description = diary.getContent();
msg.setThumbImage(bitmap);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = "webpage";
req.message = msg;
req.scene = SendMessageToWX.Req.WXSceneSession;
WinnerApplication.mWxApi.sendReq(req);
}
});
}
@Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
}
/**
* bitmap转换
*微信分享有图片,但是需要限制在32k以下,要不就分享不出去
* @param
* @return
*/
public void getImage(final String path, final HttpCallBackListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
URL imageUrl = null;
try {
imageUrl = new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
Bitmap bitmap1= createBitmapThumbnail(bitmap,false);
if (listener != null) {
listener.onFinish(bitmap1);
}
is.close();
} catch (IOException e) {
if (listener != null) {
listener.onError(e);
}
e.printStackTrace();
}
}
public Bitmap createBitmapThumbnail(Bitmap bitmap,boolean needRecycler){
int width=bitmap.getWidth();
int height=bitmap.getHeight();
int newWidth=80;
int newHeight=80;
float scaleWidth=((float)newWidth)/width;
float scaleHeight=((float)newHeight)/height;
Matrix matrix=new Matrix();
matrix.postScale(scaleWidth,scaleHeight);
Bitmap newBitMap=Bitmap.createBitmap(bitmap,0,0,width,height,matrix,true);
if(needRecycler)bitmap.recycle();
return newBitMap;
}
}).start();
}
//自定义一个接口,来作为接口回调的时候使用
public interface HttpCallBackListener {
void onFinish(Bitmap bitmap);
void onError(Exception e);
}