Search code examples
javaandroidgoogle-gdk

detecte if my apk runs on glass or mobile device


i write an android app that has java and native c code.

I know this can predict if my apk currently runs on Glass with this line of code:

how can I do similar detection in native c code?

if (android.os.Build.MODEL.contains("Glass")) {


Solution

  • You sir, have two ways for doing this, both you have to use JNI:

    Option A. Create a class called "DeviceInfo", attach a static method.

    boolean isGlassDevice() {
        return android.os.Build.MODEL.contains("Glass");
    }
    

    and from your C/C++ function:

    jclass jc_your_class = (*env)->FindClass(env, "com.your.util.DeviceInfo" ); // YOUR DeviceInfo class
    jmethodID jmid_is_glass_device = (*env)->GetMethodID(env, jc_your_class, "isGlassDevice", "()Z"); // Get info method.
    
    jboolean jb_is_glass_device = (*env)->CallStaticBooleanMethod(env, jc_your_class, jmid_is_glass_device);    
    
    if (jb_is_glass_device == JNI_TRUE){
        // Your code goes here...
    }
    

    Option B. Using JNI to do all the dirty stuff:

    jclass jc_build = (*env)->FindClass(env, "android/os/Build" ); // Build class
    jfieldID jfid_kMODEL = (*env)->GetStaticFieldID(env, jc_build, "MODEL", "Ljava/lang/String;"); // MODEL attr.
    
    jstring js_model_value = (*env)->GetStaticObjectField(env, obj, jfid_kMODEL); // MODEL attr. value.
    jstring js_glass_value = (*env)->NewStringUTF(env, "Glass"); // Glass string value.
    
    const char * nat_model_value = (*env)->GetStringUTFChars( env, js_model_value, NULL ) ;
    const char * nat_glass_value = (*env)->GetStringUTFChars( env, js_glass_value, NULL ) ;
    
    if (strcmp(nat_model_value, nat_glass_value) == 0){
        // Both strings are equal
    }
    

    I prefeer the first method since it's smaller than the option B. Finally, remmember that JNI calls between JVM and your C/C++ code are pretty slow compared with Java-to-Java and C-to-C, so you need to find the way to reduce calls between Java and C/C++.