Android NDK开发(第二天)

C++文件中打印log

从android studio3.0开始,使用cmake文件编译生成so文件,首先需要在打开的项目中,从菜单栏选择 Tools > Android > SDK Manager。
点击 SDK Tools 标签。
选中 LLDB、CMake 和 NDK 旁的复选框
[图片上传失败...(image-64ec5d-1532242419051)]

我们在创建工程初始,需要勾选,选中 Include C++ Support 复选框,创建完成以后,目录结构如下:
[图片上传失败...(image-d41ab2-1532242419052)]

CMAKEList配置

在CMAKEList配置ndk生成的so文件名称,以及打印log的配置,AS已经默认帮我们配置好了,内容如下:

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
             native-lib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/cpp/native-lib.cpp)

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

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 )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
                       native-lib

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )

配置log打印

c++中添加log打印,内容固定,添加下面代码即可:

#include 
#define  LOG_TAG    "native-dev"
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...)  __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGI(...)  __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)

LOGE("liuhang test");

完整代码如下:

#include 
#include 

#include 
#define  LOG_TAG    "native-dev"
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...)  __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)

extern "C"
JNIEXPORT jstring JNICALL
Java_com_jni_test_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    LOGE("liuhang test");
    return env->NewStringUTF(hello.c_str());
}

打印如下:


image.png

使用cmake生成多个so文件

我们可以针对多个cpp文件生成同一个so,同样的,也可以生成多个so文件,如下步骤:

  • 针对不同so文件,建立不同的目录,每个目录下由单独的CMakeLists.txt文件
  • 在外层的CMakeLists.txt中,通过ADD_SUBDIRECTORY添加不同的目录配置

AS会首先通过ADD_SUBDIRECTORY找到对应的目录,在在对应目录的CMakeLists.txt文件内容,生成对应的so文件,对应的目录结构如下:


image.png

建立DataProvider类

package com.jni.test;

/**
 * Created by liuhang on 18-7-15.
 */

public class DataProvider {

    /**
     * 把java中的int传递给c语言,c语言处理完毕后,把结果相加返回给java
     * @param x
     * @param y
     * @return
     */
    public static native int add(int x, int y);

    static {
        System.loadLibrary("test-lib");
    }


}

first目录下对应的CMakeLists.txt

cmake_minimum_required(VERSION 3.4.1)

#生成so动态库
ADD_LIBRARY(native-lib SHARED native-lib.cpp)

target_link_libraries(native-lib log)

second目录下对应的CMakeLists.txt

cmake_minimum_required(VERSION 3.4.1)

#生成so动态库
ADD_LIBRARY(test-lib SHARED test-lib.cpp)

target_link_libraries(test-lib log)

对应的test-lib.cpp

#include 
#include 

#include 
#define  LOG_TAG    "liuhang"
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...)  __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)

extern "C"

/*
 * Class:     com_jni_test_DataProvider
 * Method:    add
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_com_jni_test_DataProvider_add
  (JNIEnv * env, jobject obj, jint x, jint y) {

    LOGI("x is : %d", x);
    LOGI("y is : %d", y);
    return x + y;
}



外层CMakeLists.txt

cmake_minimum_required(VERSION 3.4.1)


#添加子目录,将会调用子目录中的CMakeLists.txt
ADD_SUBDIRECTORY(first)
ADD_SUBDIRECTORY(second)

在app/build.gradle配置外层CMakeLists.txt

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "27.0.3"
    defaultConfig {
        applicationId "com.jni.test"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags "-frtti -fexceptions"
                abiFilters "armeabi", "armeabi-v7a", "x86"
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "src/main/cpp/CMakeLists.txt"  #配置外层CMakeLists.txt路径
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
}

上述externalNativeBuild标签为ndk相关配置

上述配置已经完成,(别忘了使用的使用,通过native声明本地方法,以及通过loadlibrary来加载so文件),现在编译该模块,菜单键选择如下:build --> make project,,默认生成的so文件路径在build目录下,如下:


image.png

你可能感兴趣的:(Android NDK开发(第二天))