1

android SDK中有一个类android.os.Build里面提供了若干个静态成员,通过他们可以获取关于设备的各项信息。
在cocos2d-x中可以通过jni访问到它们。
下面是我使用时的代码可以作为参考。

#include "MfMetrics.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "platform/android/jni/JniHelper.h"

#define JAVAVM cocos2d::JniHelper::getJavaVM()

NS_MF_BEGIN;

extern "C"
{
    static std::string jni_GetStaticField_string(const char* className, const char* fieldName)
    {
        std::string ret;

        do 
        {
            JNIEnv *pEnv = 0;

            if (JAVAVM->GetEnv((void**)&pEnv, JNI_VERSION_1_4) != JNI_OK)
            {
                CCLOG("Failed to get the environment using GetEnv()");
                break;
            }

            if (JAVAVM->AttachCurrentThread(&pEnv, 0) < 0)
            {
                CCLOG("Failed to get the environment using AttachCurrentThread()");
                break;
            }

            jclass classID = pEnv->FindClass(className);
            if (!classID)
            {
                CCLOG("Failed to find class of %s", className);
                break;
            }

            jfieldID fieldID = pEnv->GetStaticFieldID(classID, fieldName, "Ljava/lang/String;");
            if(!fieldID)
            {
                CCLOG("Failed to find field of %s", fieldName);
                break;
            }

            jstring jstr = (jstring)pEnv->GetStaticObjectField(classID, fieldID);

            const char* chars = pEnv->GetStringUTFChars(jstr, NULL);
            ret = chars;
            pEnv->ReleaseStringUTFChars(jstr, chars);
        } while (0);

        return ret;
    }
}

std::string MfMetrics::_getDeviceName()
{
#define CLASS_NAME "android/os/Build"
    std::string BRAND = jni_GetStaticField_string(CLASS_NAME, "BRAND");
    std::string DEVICE = jni_GetStaticField_string(CLASS_NAME, "DEVICE");
    std::string MODEL = jni_GetStaticField_string(CLASS_NAME, "MODEL");
    return BRAND + "_" + DEVICE + "(" + MODEL + ")";
}

NS_MF_END
#endif

另外附上一个Github代码库,他提供了很多主流机型的Build.MODEL值。


迷途吧
145 声望25 粉丝

看见好文章就翻译一下,发现一些细节就分享一下,也许没什么技术,只希望能被需要的人搜到。