15

我正在尝试创建一种方法来检查需要 Context 参数的 Internet 连接。JNIHelper 允许我调用带参数的静态函数,但我不知道如何“检索” Cocos2d-x Activity 类以将其用作参数。

public static boolean isNetworkAvailable(Context context) {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;
    ConnectivityManager cm =
        (ConnectivityManager) context.getSystemService(
    Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;
    }
    return haveConnectedWifi || haveConnectedMobile;
}

而C++代码是

JniMethodInfo methodInfo;
if ( !JniHelper::getStaticMethodInfo( methodInfo,
    "my/app/TestApp", "isNetworkAvailable", "(Landroid/content/Context;)Z")) {
        //error
        return;
}
CCLog( "Method found and loaded!");
methodInfo.env->CallStaticBooleanMethod( methodInfo.classID,
methodInfo.methodID);
methodInfo.env->DeleteLocalRef( methodInfo.classID);
4

3 回答 3

3

Cocos2dxActivity.java: Add this line to Cocos2dxActivity: private static Activity me = null; Remove this line from onCreate:

Cocos2dxActivity.context = getApplicationContext();

In its place put: me = this;

use :

(ConnectivityManager) me.getSystemService(
    Context.CONNECTIVITY_SERVICE);

Now you don't need to pass the context from your Jni... I know this is not the solution but for your case you don't need to worry about context from Jni.. You can simply do your work.

Hope this helps.. I used this way to send mail from android in my game. :)

于 2012-04-27T06:33:41.147 回答
2

您可以使用以下方法将 Context 对象传递给 JNI:

extern "C" {
JNIEXPORT jboolean JNICALL
Java_yournamespace_yourclassname_methodname( JNIEnv* env, jobject thiz, jobject p_context);
}

在您的 java 类上使用以下声明:

public native static boolean methodname(Context p_context);

现在您可以从您的 java 代码中调用本机函数并传递一个上下文参数。

至于获取您的应用程序类并使用它,我将使用以下代码(在 C++ 部分中):

jclass yourAppClass = env->FindClass("my/app/TestApp");
jmethodID someMethodId = env->GetStaticMethodID(yourAppClass , "methodName", "(Landroid/content/Context;)Z");
jboolean retval = env->CallStaticObjectMethod(yourAppClass , someMethodId , p_context);
于 2012-04-28T11:18:09.923 回答
1

我看到的第一个错误是您试图错误地获取该方法。

"(android/content/Context;)V"意味着您正在要求一种方法,该方法Context作为参数接收并返回void,这不是您的情况。

你的电话应该是这样的:

jclass aClass = env->FindClass("my/app/TestApp");
env->GetMethodID(aClass, "isNetworkAvailable", "(android/content/Context;)Z");

我不完全确定如何在不破坏事物或确保它会起作用的情况下传递 a Contextto 。JNI但是您可以调用getApplication()它并将其用作Context.

于 2012-04-24T13:24:29.157 回答