1. 程式人生 > >C++呼叫Android 與Android呼叫C++ 例子

C++呼叫Android 與Android呼叫C++ 例子

現在我們在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

上我們的效果圖: