您的位置:首页 > 编程语言 > C语言/C++

C++调用Android 与Android调用C++ 例子

2013-09-14 16:45 190 查看
现在我们在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调用然后在函数里面又调用了Java
JNIEXPORT 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 := -llog

LOCAL_MODULE := cocos2dinput

LOCAL_SRC_FILES :=./jni.cpp

include $(BUILD_SHARED_LIBRARY)


记得用NDK编译,编译命令是:

ndk-build


上我们的效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: