1:創建 Creator項目,如下
2.創建完成后,項目工程圖如下
3.assets目錄創建Login場景,創建TS目錄,創建TSSDKTool.ts,Login.ts,如下圖
export class TSSDKTool { public static isAndroid = cc.sys.isNative && cc.sys.os === cc.sys.OS_ANDROID public static isIOS = cc.sys.isNative && cc.sys.os === cc.sys.OS_IOS /** * 調取native微信授權 */ public static wxLogin() { console.log("wxLogin"); if (this.isAndroid) { //調用Java代碼進行微信登錄 jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "weixin_login", "(Ljava/lang/String;)V","weixin_login"); } } /** * 接收native微信授權的code * @param errCode */ public static wxLoginResult(errCode) { console.log("wxLoginResultcode=" + errCode) if (this.isAndroid) { } } } cc["TSSDKTool"] = TSSDKTool;
5.Login.ts腳本內容如下:
// Learn TypeScript: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html // Learn Attribute: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html // Learn life-cycle callbacks: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html import { TSSDKTool } from "./TSSDKTool"; const {ccclass, property} = cc._decorator; @ccclass export default class NewClass extends cc.Component { @property(cc.Label) label: cc.Label = null; @property text: string = 'hello'; // LIFE-CYCLE CALLBACKS: onLoginWX(){ TSSDKTool.wxLogin(); } // onLoad () {} start () { } // update (dt) {} }
6.Creator編輯中將Login.ts與微信登錄按鈕綁定,如下圖:
7.構建項目(構建為Android項目)
7-1、Creator編輯器菜單欄->項目->構建發布...
7-2、相關設置如下圖
備注:選項3中的包名需與微信開發平台申請的包名一致
執行構建,
7-3、構建完成
備注:構建完成后,不要關閉窗口,最后還要來編繹
7-4、構建完成后的項目位置
8、使用Android Studio打開項目
備注:后面的目錄,文件,代碼操作都在選項5目錄中操作
9、打開build.gradle配置,翻最下面,添加微信配置:
如圖:
<!--微信授權登陸--> <activity android:name= ".wxapi.WXEntryActivity" android:label="@string/app_name" android:launchMode="singleTask" android:screenOrientation="portrait" android:theme="@android:style/Theme.Translucent" android:exported="true" />
完整內容如下
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jh.bygs.fish" android:installLocation="auto"> <uses-feature android:glEsVersion="0x00020000" /> <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"/> <application android:allowBackup="true" android:label="@string/app_name" android:icon="@mipmap/ic_launcher"> <!-- Tell Cocos2dxActivity the name of our .so --> <meta-data android:name="android.app.lib_name" android:value="cocos2djs" /> <activity android:name="org.cocos2dx.javascript.AppActivity" android:screenOrientation="sensorLandscape" android:configChanges="orientation|keyboardHidden|screenSize" android:label="@string/app_name" android:usesCleartextTraffic="true" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:launchMode="singleTask" android:taskAffinity="" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!--微信授權登陸--> <activity android:name= ".wxapi.WXEntryActivity" android:label="@string/app_name" android:launchMode="singleTask" android:screenOrientation="portrait" android:theme="@android:style/Theme.Translucent" android:exported="true" /> </application> </manifest>
11、進入目錄proj.android-studio\app\src\,准備創建微信API目錄,舉例你的包名為a.b.c.d,哪么就在src目錄創建a\b\c\d\wxapi
備注:這里很不能錯,錯了微信回調就會失敗,創建的目錄必須與你在微信開發平台申請使用的包名一致。
12、wxapi目錄(見步驟11)創建WXEntryActivity.java(必須是這個文件名)文件,文件內容如下:
備注:文件內容的第一行,修改為你的包名
package 您的包名.wxapi; import android.app.Activity; import android.os.Bundle; import android.os.Message; import android.widget.Toast; import com.tencent.mm.opensdk.modelbase.BaseReq; import com.tencent.mm.opensdk.modelbase.BaseResp; import com.tencent.mm.opensdk.modelmsg.SendAuth; import com.tencent.mm.opensdk.openapi.IWXAPI; import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler; import org.cocos2dx.javascript.AppActivity; import android.util.Log; import java.util.ArrayList; public class WXEntryActivity extends Activity implements IWXAPIEventHandler { public static int ReqState = -1;// 0為登錄, 1為分享 // private IWXAPIAPI; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.e("tt","wxEntryActivity onCreate"); // 這句話很關鍵 try { AppActivity.wx_api.handleIntent(getIntent(), this); } catch (Exception e) { e.printStackTrace(); } } @Override public void onReq(BaseReq baseReq) { System.out.println("Enter the onResp"); } // 向微信發送的請求的響應信息回調該方法 // @Override public void onResp(BaseResp baseResp) { System.out.println("Enter the onResp"); if(baseResp.errCode == BaseResp.ErrCode.ERR_OK){ // String code = ((SendAuth Resp) baseResp).code; String code = ((SendAuth.Resp) baseResp).code; System.out.println("==========code is ===========" + code); AppActivity.callJsFunction(code); finish(); } } }
13、進入目錄app\src\org\cocos2dx\javascript,修改AppActivity.java文件,文件內容如下
備注1:第44行代碼導入的包頭修改為你的包名
備注2:第53行代碼,將appid設置為微信開發申請的appid
/**************************************************************************** Copyright (c) 2015-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ package org.cocos2dx.javascript; //新增代碼 import android.util.Log; import org.cocos2dx.lib.Cocos2dxActivity; import org.cocos2dx.lib.Cocos2dxGLSurfaceView; //新增代碼 import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge; import android.os.Bundle; import android.content.Intent; import android.content.res.Configuration; //新增代碼 import com.tencent.mm.opensdk.modelmsg.SendAuth; //新增代碼 import com.tencent.mm.opensdk.openapi.IWXAPI; //新增代碼 import com.tencent.mm.opensdk.openapi.WXAPIFactory; //新增代碼 import static org.cocos2dx.lib.Cocos2dxHelper.getActivity; //新增代碼 import com.tencent.mm.opensdk.modelbase.BaseReq; //新增代碼 import com.tencent.mm.opensdk.modelbase.BaseResp; //新增代碼 import 您的包名.wxapi.WXEntryActivity; //新增代碼 import java.util.Timer; //新增代碼 import java.util.TimerTask; public class AppActivity extends Cocos2dxActivity { //新增代碼 public static String wx_appid = "您的appid"; public static IWXAPI wx_api; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //新增代碼 Log.e("tt","AppActivity onCreate"); // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508 if (!isTaskRoot()) { // Android launched another instance of the root activity into an existing task // so just quietly finish and go away, dropping the user back into the activity // at the top of the stack (ie: the last state of this task) // Don't need to finish it again since it's finished in super.onCreate . return; } //新增代碼 weixin_Init(); // DO OTHER INITIALIZATION BELOW SDKWrapper.getInstance().init(this); } //新增代碼 public static void weixin_Init() { wx_api = WXAPIFactory.createWXAPI(getActivity(),wx_appid,true); wx_api.registerApp(wx_appid); } //新增代碼 public static void weixin_login(String data) { Log.e("tt","AppActivity weixin_login"); SendAuth.Req req =new SendAuth.Req(); req.scope ="snsapi_userinfo"; req.state = data; System.out.println("req is " + req); //利用微信api發送請求 wx_api.sendReq(req); } //新增代碼(回調函數) public static void callJsFunction(final String value) { System.out.println("Enter the callJsFunction" + value); final String exes = "cc.TSSDKTool.wxLoginResult(\""+ value + "\")"; // app.runOnGLThread(new Runnable() { // @Override // public void run() { // Cocos2dxJavascriptJavaBridge.evalString(exes);//直接調用到js里面 // } // }); TimerTask task = new TimerTask(){ public void run(){ //execute the task Cocos2dxGLSurfaceView.getInstance().queueEvent(new Runnable() { @Override public void run() { System.out.println("chenggong == "+ exes); Cocos2dxJavascriptJavaBridge.evalString(exes); } }); } }; Timer timer = new Timer(); timer.schedule(task, 500); } @Override public Cocos2dxGLSurfaceView onCreateView() { Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this); // TestCpp should create stencil buffer glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8); SDKWrapper.getInstance().setGLSurfaceView(glSurfaceView, this); return glSurfaceView; } @Override protected void onResume() { super.onResume(); SDKWrapper.getInstance().onResume(); } @Override protected void onPause() { super.onPause(); SDKWrapper.getInstance().onPause(); } @Override protected void onDestroy() { super.onDestroy(); SDKWrapper.getInstance().onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); SDKWrapper.getInstance().onActivityResult(requestCode, resultCode, data); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); SDKWrapper.getInstance().onNewIntent(intent); } @Override protected void onRestart() { super.onRestart(); SDKWrapper.getInstance().onRestart(); } @Override protected void onStop() { super.onStop(); SDKWrapper.getInstance().onStop(); } @Override public void onBackPressed() { SDKWrapper.getInstance().onBackPressed(); super.onBackPressed(); } @Override public void onConfigurationChanged(Configuration newConfig) { SDKWrapper.getInstance().onConfigurationChanged(newConfig); super.onConfigurationChanged(newConfig); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { SDKWrapper.getInstance().onRestoreInstanceState(savedInstanceState); super.onRestoreInstanceState(savedInstanceState); } @Override protected void onSaveInstanceState(Bundle outState) { SDKWrapper.getInstance().onSaveInstanceState(outState); super.onSaveInstanceState(outState); } @Override protected void onStart() { SDKWrapper.getInstance().onStart(); super.onStart(); } }
14、回到Creator編輯器,執行編繹選項
15、編繹結束后,生成的apk在目錄build\jsb-link\publish\android下。
16、至此結束 。