一、获取帮助文档并下载相关资料
首先打开微信开放平台:https://open.weixin.qq.com/ 如果没有注册,请先注册并上传开发者资料等待审核。
资源中心----移动应用开发----分享与收藏功能----Android开发手册
开发手册链接地址:https://open.weixin.qq.com/zh_CN/htmledition/res/dev/document/sdk/android/index.html
资源中心----移动应用开发----接入指南---Android接入指南(下面我们主要参考这个)
二、接入微信分享功能
1、申请AppID
如何现在没有AppID可以先下载官方的Demo使用Demo中的AppID即可。
SDK和Demo下载地址:https://open.weixin.qq.com/cgi-bin/frame?t=resource/res_main_tmpl&verify=1&lang=zh_CN&target=res/app_download_android
使用微信分享、登录、收藏、支付等功能需要的库以及文件。点击下载 Android开发工具包
使用微信语音识别接口、语音合成接口。点击下载 语音SDK+Demo+开发文档
使用微信图像识别接口。点击下载 图像SDK+Demo+开发文档
使用微信卡券功能接口。点击下载 卡券SDK+开发文档
2、下载微信开发工具包(在上面已经下载)
3、开始搭建开发环境然后将libammsdk.jar文件拷贝到工程lib目录下。
注意:如果使用的是Demo中的AppID则包名一定要先和Demo的包名一致,否则分享会出错。
4、新建一个Activity在里面放置一个按钮
package net.sourceforge.simcpux; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.example.weixinsharedemo.share.WeixinShareManager; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.share_weibo); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { WeixinShareManager wsm = WeixinShareManager.getInstance(MainActivity.this); wsm.shareByWeixin(wsm.new ShareContentPic(R.drawable.ic_launcher), WeixinShareManager.WEIXIN_SHARE_TYPE_TALK); } }); } }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/share_weibo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="分享到微信"/> </RelativeLayout>4、开始创建我们的分享逻辑类并实现需要的分享功能
package com.example.weixinsharedemo.share; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.Toast; import com.example.weixinsharedemo.util.WeixiShareUtil; import com.tencent.mm.sdk.modelmsg.SendMessageToWX; import com.tencent.mm.sdk.modelmsg.WXImageObject; import com.tencent.mm.sdk.modelmsg.WXMediaMessage; import com.tencent.mm.sdk.modelmsg.WXTextObject; import com.tencent.mm.sdk.modelmsg.WXWebpageObject; import com.tencent.mm.sdk.openapi.IWXAPI; import com.tencent.mm.sdk.openapi.WXAPIFactory; /** * 实现微信分享功能的核心类 * @author Administrator * */ public class WeixinShareManager{ private static final int THUMB_SIZE = 150; /** * 文字 */ public static final int WEIXIN_SHARE_WAY_TEXT = 1; /** * 图片 */ public static final int WEIXIN_SHARE_WAY_PIC = 2; /** * 链接 */ public static final int WEIXIN_SHARE_WAY_WEBPAGE = 3; /** * 会话 */ public static final int WEIXIN_SHARE_TYPE_TALK = SendMessageToWX.Req.WXSceneSession; /** * 朋友圈 */ public static final int WEIXIN_SHARE_TYPE_FRENDS = SendMessageToWX.Req.WXSceneTimeline; private static WeixinShareManager instance; private static String weixinAppId; private IWXAPI wxApi; private Context context; private WeixinShareManager(Context context){ this.context = context; //初始化数据 weixinAppId = WeixiShareUtil.getWeixinAppId(context); //初始化微信分享代码 if(weixinAppId != null){ initWeixinShare(context); } } /** * 获取WeixinShareManager实例 * 非线程安全,请在UI线程中操作 * @return */ public static WeixinShareManager getInstance(Context context){ if(instance == null){ instance = new WeixinShareManager(context); } return instance; } private void initWeixinShare(Context context){ wxApi = WXAPIFactory.createWXAPI(context, weixinAppId, true); wxApi.registerApp(weixinAppId); } /** * 通过微信分享 * @param shareWay 分享的方式(文本、图片、链接) * @param shareType 分享的类型(朋友圈,会话) */ public void shareByWeixin(ShareContent shareContent, int shareType){ switch (shareContent.getShareWay()) { case WEIXIN_SHARE_WAY_TEXT: shareText(shareType, shareContent); break; case WEIXIN_SHARE_WAY_PIC: sharePicture(shareType, shareContent); break; case WEIXIN_SHARE_WAY_WEBPAGE: shareWebPage(shareType, shareContent); break; } } private abstract class ShareContent{ protected abstract int getShareWay(); protected abstract String getContent(); protected abstract String getTitle(); protected abstract String getURL(); protected abstract int getPicResource(); } /** * 设置分享文字的内容 * @author Administrator * */ public class ShareContentText extends ShareContent{ private String content; /** * 构造分享文字类 * @param text 分享的文字内容 */ public ShareContentText(String content){ this.content = content; } @Override protected String getContent() { return content; } @Override protected String getTitle() { return null; } @Override protected String getURL() { return null; } @Override protected int getPicResource() { return -1; } @Override protected int getShareWay() { return WEIXIN_SHARE_WAY_TEXT; } } /** * 设置分享图片的内容 * @author Administrator * */ public class ShareContentPic extends ShareContent{ private int picResource; public ShareContentPic(int picResource){ this.picResource = picResource; } @Override protected String getContent() { return null; } @Override protected String getTitle() { return null; } @Override protected String getURL() { return null; } @Override protected int getPicResource() { return picResource; } @Override protected int getShareWay() { return WEIXIN_SHARE_WAY_PIC; } } /** * 设置分享链接的内容 * @author Administrator * */ public class ShareContentWebpage extends ShareContent{ private String title; private String content; private String url; private int picResource; public ShareContentWebpage(String title, String content, String url, int picResource){ this.title = title; this.content = content; this.url = url; this.picResource = picResource; } @Override protected String getContent() { return content; } @Override protected String getTitle() { return title; } @Override protected String getURL() { return url; } @Override protected int getPicResource() { return picResource; } @Override protected int getShareWay() { return WEIXIN_SHARE_WAY_WEBPAGE; } } /* * 分享文字 */ private void shareText(int shareType, ShareContent shareContent) { String text = shareContent.getContent(); //初始化一个WXTextObject对象 WXTextObject textObj = new WXTextObject(); textObj.text = text; //用WXTextObject对象初始化一个WXMediaMessage对象 WXMediaMessage msg = new WXMediaMessage(); msg.mediaObject = textObj; msg.description = text; //构造一个Req SendMessageToWX.Req req = new SendMessageToWX.Req(); //transaction字段用于唯一标识一个请求 req.transaction = buildTransaction("textshare"); req.message = msg; //发送的目标场景, 可以选择发送到会话 WXSceneSession 或者朋友圈 WXSceneTimeline。 默认发送到会话。 req.scene = shareType; wxApi.sendReq(req); } /* * 分享图片 */ private void sharePicture(int shareType, ShareContent shareContent) { Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), shareContent.getPicResource()); WXImageObject imgObj = new WXImageObject(bmp); WXMediaMessage msg = new WXMediaMessage(); msg.mediaObject = imgObj; Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true); bmp.recycle(); msg.thumbData = WeixiShareUtil.bmpToByteArray(thumbBmp, true); //设置缩略图 SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("imgshareappdata"); req.message = msg; req.scene = shareType; wxApi.sendReq(req); } /* * 分享链接 */ private void shareWebPage(int shareType, ShareContent shareContent) { WXWebpageObject webpage = new WXWebpageObject(); webpage.webpageUrl = shareContent.getURL(); WXMediaMessage msg = new WXMediaMessage(webpage); msg.title = shareContent.getTitle(); msg.description = shareContent.getContent(); Bitmap thumb = BitmapFactory.decodeResource(context.getResources(), shareContent.getPicResource()); if(thumb == null){ Toast.makeText(context, "图片不能为空", Toast.LENGTH_SHORT).show(); }else{ msg.thumbData = WeixiShareUtil.bmpToByteArray(thumb, true); } SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("webpage"); req.message = msg; req.scene = shareType; wxApi.sendReq(req); } private String buildTransaction(final String type) { return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis(); } }上面只是实现了文字、图片、链接的分享功能,如需分享视频、音频可以添加。
5、实现分享结果反馈
要实现分享结果的反馈,微信已经将结果的处理封装到了WXEntryActivity中(jar包中),所以我们要继承该类获取反馈结果。
在你的包名相应目录下新建一个wxapi目录,并在该wxapi目录下新增一个WXEntryActivity类,该类继承自Activity(例如应用程序的包名为net.sourceforge.simcpux,则新添加的类如下图所示)
package net.sourceforge.simcpux.wxapi; import com.example.weixinsharedemo.share.WXCallbackActivity; public class CallBackActivity extends WXCallbackActivity{ @Override public void weixinResp(int respCode) { System.out.println("respCode = " + respCode); } }注意:记得去Mainfest文件中注册Activity
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.sourceforge.simcpux" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="net.sourceforge.simcpux.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="net.sourceforge.simcpux.wxapi.CallBackActivity" android:label="@string/app_name" android:exported="true"></activity> <meta-data android:name="WEIXIN_APP_ID" android:value="你的AppId"/> </application> </manifest>
三、运行代码
使用Demo中AppId的朋友在这里要注意,请设置一下签名文件(在上面下载的SDK中有)如下:点击Browser进行选择,运行即可。
如果有什么问题请在下面留言,也可以加博客旁边的QQ群(142979499)进行详细交流。另外可以关注一下我的阳光小栈(www.sunhome.aliapp.com)。