Android Studio使用CMake编译JNI初探

来源:互联网 发布:淘宝有哪些孕妇装店 编辑:程序博客网 时间:2024/05/22 13:23

     Android Studio2.2出来后,通过CMake构建工具,能更方便的对NDK进行开发,相比过去,CMake支持代码提示、代码跳转、断点等方便的功能。下面进入正题:

一、创建支持 C/C++ 的新项目

1.新建支持CMake的项目



  • Exceptions Support
    如果选中复选框,则表示当前项目支持C++异常处理

  • Runtime Type Information Support
    选中复选框,项目支持RTTI

2.声明需要调用的方法

项目生成成功后,会在MainActivity上自动生成使用方法



当然也可以把方法统一放到一个类中,我创建了一个JniUtil进行处理

public class JniUtil {    static {        System.loadLibrary("test-lib"); //要求与CMakeLists.txt中的一致    }    public static native String stringFromSelf(String str);     public static native  int square(int num);   }


3.编写C/C++代码实现方法

接下来就是通过C/C++来对声明的方法进行实现,具体格式可以参照系统自动生成的native-lib.cpp文件,我创建了testJni.cpp进行实现

#include <jni.h>#include <string>#include <android/log.h>#define LOG_TAG    "lmj -- JNILOG" // 这个是自定义的LOG的标识#define LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG, __VA_ARGS__)extern "C"JNIEXPORT jstring JNICALLJava_com_example_win7_jnitest_util_JniUtil_stringFromSelf(        JNIEnv *env,        jobject /* this */, jstring name) {    char preString[10] = "Hello ";    const char *strName = env->GetStringUTFChars(name, false);    char result[100];    strcpy(result, preString);    strcat(result, strName);    LOGE("log.e 传入的名字:%s", strName);    return env->NewStringUTF(result);}extern "C"JNIEXPORT jint JNICALLJava_com_example_win7_jnitest_util_JniUtil_square(        JNIEnv *env,        jobject /* this */, jint num) {    LOGE("log.e 传入的数字:%d", num);    return num * num;}

4.配置

打开CMakeLists.txt进行配置,系统已经为我们自动生成了,我们需要做一些小小的改动



需要修改的点
(1)add_library():配置so库信息

add_library( # Sets the name of the library.             test-lib        #library的名字,即System.loadLibrary方法所需的参数             # Sets the library as a shared library.             SHARED        #STATIC:表示静态的.a的库、 SHARED:表示.so的库。             # Provides a relative path to your source file(s).             src/main/cpp/testJni.cpp )   #文件路径

(3)find_library():如果需要使用NDK的Apis或者库,则要写该方法,没用到的话就不用写了

例如我需要用到Log这个api:

find_library( # Sets the name of the path variable.              log-lib              # Specifies the name of the NDK library that              # you want CMake to locate.              log )


(2)target_link_libraries():将两者关联

target_link_libraries( # Specifies the target library.                       test-lib     #要关联的库名                       # Links the target library to the log library                       # included in the NDK.                       ${log-lib} )


5.调用

我一共写了两个测试方法,一个返回字符串,一个返回传入数字的平方。

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    // Example of a call to a native method    final TextView tv = (TextView) findViewById(R.id.sample_text);        final EditText num = (EditText)findViewById(R.id.num);        Button equal = (Button)findViewById(R.id.equal);        final TextView result = (TextView)findViewById(R.id.result);        equal.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                int count = Integer.parseInt(num.getText().toString());  //获取数字                String strResult = String.valueOf(JniUtil.square(count));  //计算平方                result.setText(strResult);                                //显示结果            }        });        EditText name = (EditText)findViewById(R.id.name);        name.addTextChangedListener(new TextWatcher() {            @Override            public void beforeTextChanged(CharSequence s, int start, int count, int after) {            }            @Override            public void onTextChanged(CharSequence s, int start, int before, int count) {                tv.setText(JniUtil.stringFromSelf(s.toString()));     //返回字符串            }            @Override            public void afterTextChanged(Editable s) {            }        });    }}

附Demo下载地址。





原创粉丝点击