• cocos2dx 通过jni调用安卓底层方法


    cocos2dx通过封装JniHelper类来调用安卓api底层函数,该文件在cocos/platform/android/jni/JniHelper.h,使用方法如下:

    打开eclipse,导入cocos2dx的项目为安卓项目,如下所示:

    新建一个java文件在org.cocos2dx.lib包下,起名为

    Cocos2dxTestJni.java,里面添加一个单例的静态方法和一个成员函数(判断是否开启wifi),如下所示:

    package org.cocos2dx.lib;

    import android.content.Context;

    import android.net.ConnectivityManager;

    import android.net.NetworkInfo;

    public class Cocos2dxTestJni {

    private static Cocos2dxTestJni instance = null;

    public static Object getInstance()

    {

    if(instance == null)

    instance = new Cocos2dxTestJni();

    return instance;

    }

    public boolean  bOpenWifi()

    {

    Context context = Cocos2dxActivity.getContext();

    ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();

    if(activeNetInfo != null &&  activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI)

    {

    System.out.println("wifi is open");

    return true;

    }

    System.out.println("wifi is close");

    return false;

    }

    }

    在c++层调用安卓底层函数,首先包含头文件:

    #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

    #include "platform/android/jni/JniHelper.h"

    #include <jni.h>

    #endif

    调用方法如下:

    #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

        JniMethodInfo info;

        bool ret = JniHelper::getStaticMethodInfo(info,"org/cocos2dx/lib/Cocos2dxTestJni","getInstance","()Ljava/lang/Object;");

        jobject jobj;

        if(ret)

        {

            log("success to call getInstance Func");

            jobj = info.env->CallStaticObjectMethod(info.classID,info.methodID);

        

            bool ret2 = JniHelper::getMethodInfo(info,"org/cocos2dx/lib/Cocos2dxTestJni","bOpenWifi","()Z");

            

            if(ret2)

            {

                jboolean jb = info.env->CallBooleanMethod(jobj,info.methodID);

                if(jb == JNI_TRUE)

                    log("success Call bOpenWifi");

                else

                    log("no wifi open");

            }

        }

        else

        {

            log("failed to call getInstance Func");

        }

    #endif

    JniHelper::getStaticMethodInfo方法是根据脚本文件路径、函数名字、签名缩写来获取方法的具体信息,包括类id,方法id,运行环境等,保存在JniMethodInfo的变量中,

    info.env->CallStaticObjectMethod(info.classID,info.methodID);通过类id,方法id调用函数,然后放回一个jobject类型。

    具体其他函数可以查看unity圣典的api文档:http://game.ceeger.com/Script/AndroidJNI/AndroidJNI.html

    jni的签名缩写的缩写如下表所示:

    jni的返回类型如下:

    将cocos项目打包成apk包,打开eclipse调试,查看输出

    笔者很懒,暂时先写到这里

  • 相关阅读:
    iOS-Core Text 入门
    Mac浏览器全屏设置
    Quartz 2D - 图形上下文(Graphics Contexts)
    Quartz 2D 概述
    Quartz 2D官方文档翻译(持续更新中)
    那些年,我们常掉进去的坑
    CGAffineTransformMake(a,b,c,d,tx,ty) 矩阵运算的原理 (转载)
    科大讯飞
    Object-C语言类的扩展
    科大讯飞语音识别
  • 原文地址:https://www.cnblogs.com/HemJohn/p/4922692.html
Copyright © 2020-2023  润新知