现在我们在Android上玩到的游戏,大都是由C++编写的,然后通过NDK编译,才能运行在Android上。而C++与Android之间的交互,通过NDK这个编译工具。那么C++与Android之间是如何交互的?
Android调用C++,我们通过从C++返回一个String来作为例子。
C++调用Android,这里通过弹出一个提示框。
Android工程名:com.example.cocos2dinput
Activity名:MainActivity
首先是Android层的MainActivity源代码:
public class MainActivity extends Activity { TextView ContentTextView; Button buttonCallC; String contentString; public static Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contentString=getStringFromC(); ContentTextView=(TextView)findViewById(R.id.text1); ContentTextView.setText(contentString); button=(Button)findViewById(R.id.button1); buttonCallC=(Button)findViewById(R.id.button2); mContext=this.getApplicationContext(); buttonCallC.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub callShowMessage(); } }); } public void showMessage() { Log.d("showMessage", "showMessage"); AlertDialog.Builder builder=new Builder(this); builder.setTitle("C++调用Android"); builder.setMessage("这是一个C++调用Android的例子"); builder.show(); } public native String callShowMessage(); public native String getStringFromC(); @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } static{ System.loadLibrary("cocos2dinput"); }}
下面是jni.cpp
#include<string.h>#include<jni.h>#include<android/log.h>JNIEnv *g_env;jobject *g_object;extern "C"{JNIEXPORT jstring JNICALL Java_com_example_cocos2dinput_MainActivity_getStringFromC(JNIEnv* env,jobject thiz){ return env->NewStringUTF("callCMessageBox");}//下面的函数首先被Android调用然后在函数里面又调用了JavaJNIEXPORT jint JNICALL Java_com_example_cocos2dinput_MainActivity_callShowMessage(JNIEnv* env,jobject thiz){ jmethodID notification_method = env->GetMethodID(env->GetObjectClass(thiz),"showMessage","()V"); env->CallVoidMethod(thiz,notification_method); return 0;}}
Android.mk
LOCAL_PATH := $(call my-dir)include $(CLEAR_VARS)LOCAL_LDLIBS := -llogLOCAL_MODULE := cocos2dinputLOCAL_SRC_FILES :=./jni.cppinclude $(BUILD_SHARED_LIBRARY)
记得用NDK编译,编译命令是:
ndk-build
上我们的效果图:
再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow