首页 > 代码库 > [工作积累] NDK通过Java获取package name 和version

[工作积累] NDK通过Java获取package name 和version

////////////////////////////////////////////////////////////////////////////Java code snippet//get APK‘s versionCode in AndroidManifest.xmlpublic int getVersionCode() {int versionCode = 1;try{PackageInfo packageInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);versionCode = packageInfo.versionCode;}catch (NameNotFoundException e) {Log.d(TAG, "cannot get package info.");}return versionCode;}

 

// --------------------------------------------------------------------
// C code snippet: helper function to get package name from Java// --------------------------------------------------------------------static bool Android_GetPackageName(char* outPackageName, size_t length) {    Android_App* app = Android_GetApp();    ANativeActivity*activity = app->activity;    JNIEnv* env = activity->env;    //note: we need to attach dalvik VM to current thread, as it is not main thread    JavaVM* vm = activity->vm;    if ( (*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_6) < 0 )        (*vm)->AttachCurrentThread(vm, &env, NULL);    //get package name from Activity Class(context)    jclass android_content_Context = (*env)->GetObjectClass(env, activity->clazz);    jmethodID midGetPackageName = (*env)->GetMethodID(env, android_content_Context, "getPackageName", "()Ljava/lang/String;");    jstring PackageName= (jstring)(*env)->CallObjectMethod(env, activity->clazz, midGetPackageName);    bool ret = false;    if( PackageName != null ) {        //jchar is UTF16        jsize len = (*env)->GetStringLength(env, PackageName);        const jchar* jcharBuff = (*env)->GetStringChars(env, PackageName, NULL);        //Copy jcharBuff to outPckageName with code conversion(UTF16 to UTF8)        #error do code conversion        (*env)->DeleteLocalRef(env, PackageName);    }    (*env)->DeleteLocalRef(env, android_content_Context);    return ret;}// --------------------------------------------------------------------// helper function to get package version code from Java// --------------------------------------------------------------------static int Android_GetVersionCode() {    Android_App* app = Android_GetApp();    ANativeActivity*activity = app->activity;    //get version code from Java    JNIEnv* env = activity->env;    //note: we need to attach dalvik VM to current thread, as it is not main thread    JavaVM* vm = activity->vm;    if ( (*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_6) < 0 )        (*vm)->AttachCurrentThread(vm, &env, NULL);    jclass ActivityClass = (*env)->GetObjectClass(env, activity->clazz);    jmethodID java_method = (*env)->GetMethodID(env, ActivityClass, (char8*)"getVersionCode", (char8*)"()I");    assert( java_method != NULL );    jint ret = (*env)->CallIntMethod(env, activity->clazz , java_method);    (*env)->DeleteLocalRef(env, ActivityClass);    return (int)ret;}