您的位置:首页 > 移动开发 > Android开发

Android NDK 入门1

2018-01-08 13:54 260 查看

新建一个包含C++支持的新项目



注意关键的一步,就是勾选“include C++ support”,其他我这里均选择默认。

运行项目



运行的结果,可以看到,屏幕中央出现了“Hello from c++”.

基本结构

调用代码

public class MainActivity extends AppCompatActivity {

// Used to load the 'native-lib' library on application startup.
// 加载原生库
static {
System.loadLibrary("native-lib");
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Example of a call to a native method
// 调用原生库的方法
TextView tv = (TextView) findViewById(R.id.sample_text);
tv.setText(stringFromJNI());
}

/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
// 原生方法声明
public native String stringFromJNI();
}


原生代码

#include <jni.h>
#include <string>

extern "C"
JNIEXPORT jstring

JNICALL
Java_com_demo_fww_ndkdemo1_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";// 屏幕中显示的字符串,就是从这里传过去的。
return env->NewStringUTF(hello.c_str());
}


添加自己的方法

在原生方法声明的下面加一个方法声明,一个简单的加法计算:

public native int add(int a, int b);


添加新方法的调用代码:

// Example of a call to a native method
TextView tv = (TextView) findViewById(R.id.sample_text);
tv.setText(stringFromJNI());
tv.setText(Integer.toString(add(1,3)));// 4
tv.setText("a+b结果为:" + add(1,3));// a+b结果为:4


照猫画虎,添加原生代码:

extern "C"
JNIEXPORT jint
JNICALL
Java_com_demo_fww_ndkdemo1_MainActivity_add(
JNIEnv *env,
jobject /* this */,
jint a,
jint b) {
return a + b;
}


新的运行结果



通过以上操作,我们添加了一个简单的加法运算方法,可想而知,我们可以用同样的方法添加更有用的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: