How can I detect the Android runtime (Dalvik or ART)?

前端 未结 6 1116
长情又很酷
长情又很酷 2021-01-30 13:22

Google added a new ART runtime with Android 4.4. How can I determine whether ART or Dalvik is the current runtime?

6条回答
  •  佛祖请我去吃肉
    2021-01-30 14:18

    For anyone needing a JNI version:

    #include 
    
    static bool isArtEnabled() {
        char buf[PROP_VALUE_MAX] = {};
        __system_property_get("persist.sys.dalvik.vm.lib.2", buf);
        // This allows libartd.so to be detected as well.
        return strncmp("libart", buf, 6) == 0;
    }
    

    Or if you want to follow a code path closer to what shoe rat posted,

    static bool isArtEnabled(JNIEnv *env)
    {
        // Per https://developer.android.com/guide/practices/verifying-apps-art.html
        // if the result of System.getProperty("java.vm.version") starts with 2,
        // ART is enabled.
    
        jclass systemClass = env->FindClass("java/lang/System");
    
        if (systemClass == NULL) {
            LOGD("Could not find java.lang.System.");
            return false;
        }
    
        jmethodID getProperty = env->GetStaticMethodID(systemClass,
            "getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
    
        if (getProperty == NULL) {
            LOGD("Could not find java.lang.System.getProperty(String).");
            return false;
        }
    
        jstring propertyName = env->NewStringUTF("java.vm.version");
    
        jstring jversion = (jstring)env->CallStaticObjectMethod(
            systemClass, getProperty, propertyName);
    
        if (jversion == NULL) {
            LOGD("java.lang.System.getProperty('java.vm.version') did not return a value.");
            return false;
        }
    
        const char *version = env->GetStringUTFChars(jversion, JNI_FALSE);
    
        // Lets flip that check around to better bullet proof us.
        // Consider any version which starts with "1." to be Dalvik,
        // and all others to be ART.
        bool isArtEnabled = !(strlen(version) < 2 ||
            strncmp("1.", version, 2) == 0);
    
        LOGD("Is ART enabled? %d (%s)", isArtEnabled, version);
    
        env->ReleaseStringUTFChars(jversion, version);
    
        return isArtEnabled;
    }
    

提交回复
热议问题