NativeActivity通过jni调用java层的Android API

Gretchen ·
更新时间:2024-11-10
· 882 次阅读

1. 继承Nativity,打通native和java层

public class MyNativeActivity extends NativeActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.v("test","oncreate"); } public void LoadWebSite(String url){ Log.v("test", "GetWebPicture, url is:" + url); } }

2. 修改AndroidManifest,让他启动你继承后的MyNativeActivity,而不是原生的NativeActivity 。

把 activity android:name="android.app.NativeActivity" 改成 activity android:name=".MyNativeActivity"

这样,程序启动后运行java层的onCreate,其中super.onCreate(savedInstanceState)会调用到native层的void android_main(struct android_app* state) 入口。

3. 在native code中调用java函数

void getWebPicture(struct android_app* app) { jobject activityInstance = g_app->activity->clazz; JavaVM* jvm = g_app->activity->vm; JNIEnv *env = NULL; (*jvm)->GetEnv(jvm, (void **) &env, JNI_VERSION_1_6); if ((*jvm)->AttachCurrentThread(jvm, &env, NULL) GetObjectClass(env, activityInstance); if (!clazz) { LOGE("callback_handler: failed to get WebPicCls class reference"); (*jvm)->DetachCurrentThread(app->activity->vm); return; } jmethodID methodID = (*env)->GetMethodID(env, clazz, "LoadWebSite", "(Ljava/lang/String;)V"); if (!methodID) { LOGE("callback_handler: failed to get LoadWebSite method ID"); (*jvm)->DetachCurrentThread(app->activity->vm); return; } jstring url= (*env)->NewStringUTF(env, "http://198.168.1.104"); (*env)->CallVoidMethod(env, activityInstance, methodID, url); (*env)->ReleaseStringUTFChars(env,url,(*env)->GetStringUTFChars(env, url, 0)); (*jvm)->DetachCurrentThread(jvm); } SunnyLiaoSu 原创文章 83获赞 91访问量 4万+ 关注 私信 展开阅读全文
作者:SunnyLiaoSu



用java JAVA jni api Android

需要 登录 后方可回复, 如果你还没有账号请 注册新账号