我有一个C ++ NDK插件(.so),我想修改Android上的Activity布局。这个插件需要支持推送通知和监听器接口。
为此,我知道我需要使用JNI接口来启动对Java的请求,并从UI元素接收事件。然而,我遇到的问题是我的C ++如何正确地访问JVM或JEnv。
警告所有psudo代码。我的问题和困惑是内联的。
public class MyActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new TestRenderer().Start()
}
}
class TestRenderer {
// Messages to the plugin.
void native Start();
// Messages from the plugin.
void OnCreated() {
// Do something.
}
static {
System.loadLibrary("testrenderer");
}
}
然后将调用JNI
JNIEXPORT void JNICALL Java_TestRenderer_Start(JNIEnv* env, jobject obj)
{
// Create my C++ class that does all the work!
TestRenderer renderer = new TestRenderer();
renderer.Start();
}
然而,当我的C ++ TestRenderer调用自己的Java时,我就在这里画一个空白的地方。
class TestRenderer
{
public:
...
void Start()
{
// Create a relative view.
CreateRelativeView();
}
private:
void CreateRelativeView()
{
// JNI create my java class and find method.
// Call method against against that Java class.
// What JVM, JEnv, or jobject should I use?
// AT THIS EXACT POINT I NEED ACCESS TO THE ACTIVITY CONTEXT.
// new CustomView(context); <--- ?????
}
// Also, how do I ensure I call OnCreated on the right Java object.
void OnCreated()
{
...
// Call method against Java TestRenderer on the right jobject.
}
};
现在为插件的Java
public class CustomView extends RelativeLayout {
public CustomView(Context context) {
super(context);
// Call back into native
OnCreated();
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
// Call back into native
OnCreated();
}
// My listener call I would want invoked to go back through plugin to client.
public native OnCreated();
static {
// I assume back to the same plugin?
System.loadLibrary("testrenderer");
}
}
我知道这听起来有点令人费解,但如果我能够在中间层中查看本机,它可以解决其他平台上的许多共享代码问题。我觉得这完全有可能,但我画的是空白。
提前谢谢。