在Android上,通过jni进行纯C/C++开发,经常会遇到与系统机制不协调的事情,毕竟系统的应用框架都在java层。比如调用系统输入法,就需要通过jni在java层调用。
因此如果底层的C/C++能映射到java层的activity,就比较容易处理。
网络上已经有大神说明了相关的机制,直接转过来参考:
原文地址:http://blog.sina.com.cn/s/blog_439abfdd0101k6ul.html 转载请注明
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,让他启动你继承后的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) < 0)
{
LOGE("callback_handler: failed to attach current thread");
return;
}
jclass clazz = (*env)->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);
}