1.使用AndroidStudio创建一个Empty Activity项目,如图:
2. 在File->New->New Module创建一个模块,如图:
3.复制Unity安装路径下的classes.jar包至Module项目中的Lib文件夹 :
unity:Editor\Data\PlaybackEngines\AndroidPlayer\Variations\mono\Release\Classes
记得右键添加包至项目中。
4.在src下创建一个Empty Activity,命名为MainActivity,代码如下:
public class MainActivity extends UnityPlayerActivity {
public IWXAPI wxapi = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void WechatInit(String appId){
Constants.WX_APP_ID = appId;
if(wxapi == null){ //初始化wxapi
wxapi = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID);
}
wxapi.registerApp( Constants.WX_APP_ID);
}
/**
* 调用微信登录
* @param callBackGameObjectName
* @param callBackFuncName
*/
public void WechatLogin(String callBackGameObjectName,String callBackFuncName){
if(!wxapi.isWXAppInstalled()){
return;
}
WXEntryActivity.GameObjectName = callBackGameObjectName;
WXEntryActivity.CallBackFuncName = callBackFuncName;
SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = "wechat_sdk";
wxapi.sendReq(req);
}
}
*.这里需注意的是找不到UnityPlayerActivity,解决方法:创建一个playerActivity文件夹,然后复制Unity安装路径下的 Editor\Data\PlaybackEngines\AndroidPlayer\Source\com\unity3d\player\UnityPlayerActivity.java文件至该文件夹中。如图所示
5.创建WXEntryActivity类,代码如下:
/**
*微信登录回调核心类
*/
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
public static String GameObjectName = "WXLoginObject"; //通知Unity哪个物体GameObjectName
public static String CallBackFuncName = "WXLoginCallBack";//GameObjectName的CallBackFuncName方法
public IWXAPI wxapi = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceSt