编译环境: windows7 64bit + NDK r5 + jdk6
测试环境: htc G6
因为工作需要,需要在C++代码下调用Android代码和Android代码下调用C++代码,故把实现方法记录下来。我尽量把步骤和应该注意的地方都提及,文笔不好,且代码风格皆为C++风格,请各位看官原谅。
在本文章里,需要JDK, Android NDK r5, cygwin参与编译。
简单起见,我用新的例子来说明这个过程。
主要流程的说明如下(红色函数为Android代码,蓝色函数为C++代码):
1. 点击Button,在Button响应函数里调用setName(String _strName)把EditText里的字符串传到C++代码setName()中去。
2·在C++的void setName()中,接收String,通过showNameInAndroidJNI()反向调用Android的void showNameInAndroid(String _strName),弹出对话框,显示String。
★★★★★★Android端★★★★★★★★★
以下为本程序的主界面:
////////////////////////////////////////////
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="***@string/hello"
/>
<EditText android:text=""
android:id="@+id/EditTextName"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</EditText>
<Button android:text="把上面的字符串发送到C++"
android:id="@+id/ButtonSend"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
////////////////////////////////////////////
===========Android调用C++===============
这个Android程序只有一个继承于Activity的类mainWnd:
首先要mainWnd成员里声明要在Android调用的C++函数;
public native void setName(String _strName);
native是修饰符必须的
接着在mainWnd的onCreate函数加入按钮响应
///////////按钮响应函数//////////////
Button btnSend = (Button)findViewById();
(new OnClickListener()
{
Android and C 来自淘豆网m.daumloan.com转载请标明出处.