这两天项目需求,需要做分享功能。这块之前是用shareSdk实现的,现在发现有些局限,计划用原生的微信官方提供的sdk来做。
因此,这篇文章主要是做一个整理和总结,供自己备忘和大家参考。
1.申请你的AppID
请到 开发者应用登记页面 进行登记,登记并选择移动应用进行设置后,将该应用提交审核,只有审核通过的应用才能进行开发。
2.下载微信终端开发工具包并导入
开发工具包主要包含3部分内容:(其中,只有libammsdk.jar是必须的)
-
- libammsdk.jar(每个第三方应用必须要导入该sdk库,用于实现与微信的通信)
3.添加必要的权限支持:
<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"/>
4.代码编写
微信为我们提供了丰富的接口和元素支持分享功能的实现。主要有下面几种元素
WXWebpageObject // 网页对象
WXTextObject // 文本对象
WXImageObject // 图片对象
WXMusicObject // 音乐对象
WXVideoObject // 视频对象
WXEmojiObject //Emoji表情对象
下面上代码了。
private IWXAPI api;
api = WXAPIFactory.createWXAPI(this, APPID);
api.registerApp(APPP_ID);
WXWebpageObject webpage = new WXWebpageObject();
//跳转的网页url
webpage.webpageUrl = "http://www.baidu.com";// 创建媒体消息对象
WXMediaMessage msg = new WXMediaMessage(webpage);//标题
msg.title = "WebPage Title WebPage Title WebPage Title WebPage Title WebPage Title WebPage Title WebPage Title WebPage Title WebPage Title Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long";//描述
msg.description = "WebPage Description WebPage Description WebPage Description WebPage Description WebPage Description WebPage Description WebPage Description WebPage Description WebPage Description Very Long Very Long Very Long Very Long Very Long Very Long Very Long";//分享市左边的图片(如果没有系统会有一个默认的)图片大小要求小于 32K
Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.send_music_thumb); msg.thumbData = Util.bmpToByteArray(thumb, true);//Req对象
SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("webpage"); req.message = msg;//分享到朋友圈(微信版本4.2之前不支持分享到朋友圈)
req.scene = SendMessageToWX.Req.WXSceneTimeline ;
//分享给好友
//req.scene = SendMessageToWX.Req.WXSceneSession;
api.sendReq(req);
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis(); }
下面再来看给音频的例子
WXMusicObject music = new WXMusicObject();
music.musicUrl="http://staff2.ustc.edu.cn/~wdw/softdown/index.asp/0042515_05.ANDY.mp3";
music.musicLowBandUrl = "http://www.qq.com"; //低带宽音频
WXMediaMessage msg = new WXMediaMessage();
msg.mediaObject = music; msg.title = "Music Title"; msg.description = "Music Album";Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.send_music_thumb);
msg.thumbData = Util.bmpToByteArray(thumb, true);SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("music"); req.message = msg; req.scene = SendMessageToWX.Req.WXSceneTimeline ; api.sendReq(req);
5.关于混淆
如果需要混淆代码,为了保证sdk的正常使用,需要在proguard.cfg加上下面两行配置:
-keep class com.tencent.mm.sdk.** {
*;
}
好啦,就这么多了,希望能对看到的人,有所帮助、