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

//////////////////////////////////////////////////////////////////////////

//Java code snippet

//get APK's versionCode in AndroidManifest.xml

public 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 ) {

        // get UTF8 string & copy to dest

const char* charBuff = (*env)->GetStringUTFChars(env, PackageName, NULL);

        strncpy(outPackageName, charBuff, length);
outPackageName[length-1]='\0';

(*env)->ReleaseStringUTFChars(PackageName, charBuff); (
*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; }

 通过以上方法可以动态生成OBB文件名称, 而不使用硬编码.

你可能感兴趣的:(package)