Cocos Creator微信登录接入(完全小白教程)(安卓篇)

1:创建 Creator项目,如下

 

2.创建完成后,项目工程图如下

 

3.assets目录创建Login场景,创建TS目录,创建TSSDKTool.ts,Login.ts,如下图

4. TSSDKTool.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配置,翻最下面,添加微信配置:

implementation 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'

如图:

 

10、编辑src\AndroidManifest.xml文件,添加代码

<!--微信授权登陆-->
        <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、至此结束 。

 

posted @ 2021-01-11 15:09  独一无二~  阅读(3410)  评论(0编辑  收藏  举报