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; }
新的运行结果
通过以上操作,我们添加了一个简单的加法运算方法,可想而知,我们可以用同样的方法添加更有用的方法。
相关文章推荐
- Android NDK开发轻松入门
- 【移动安全】Android NDK开发入门实例
- Android NDK开发入门学习笔记(图文教程,极其详尽)
- Android NDK编程入门笔记
- Android NDK开发入门问答
- Android NDK开发之入门教程
- Android NDK入门
- Android NDK开发入门
- Window下使用android NDK开发Android应用-入门篇
- Android NDK开发轻松入门
- Android NDK入门程序HelloWorld
- Android NDK 开发入门例子
- android ndk 入门 - 一个简单的ndk工程
- android ndk 入门3 - log实现
- Android NDK开发轻松入门
- Android NDK的入门学习过程
- Android NDK的入门程序 FATAL EXCEPTION
- Android NDK(1、简单入门和遇到的问题)
- android NDK开发、编译、调试环境搭建与操作入门
- 下面就介绍下Android NDK的入门学习过程(转)