Add C and C++ Code

如何在 Android 中使用 C 或者 C++ 代码.

我最近在做一个视频直播的项目, 需要将视频推流到服务器, 网上现在有很多已经做好的 Android 推流器, 但是我想自己使用 FFMpeg 来自己实现一个, 同时学习一下 Android 使用 C 或者 C++ 的方式.

HelloCPP

我们先看一个来自 C 的 Hello World!

新建项目

在创建项目时, 选择 Include C++ support.

15247093656280

这将为我们的项目添加一些必要的 C++ 支持的文件, 下面我们将仔细分析这些文件.

文件结构

C++ 和 C 支持的 Android Studio 工程的目录结构有些不同, 我们分 Android 视图和 Project 视图来分别看一下

Android 视图
15247102352563-w453

Android 视图的项目结构如上图所示.

从大的角度来看, 除了 app module 和 Gradle Scripts 之外, 多出来了一个是 External Build Files 这个目录. External Build Files 包含了一个 CMakeLists.txt 文件, Android Studio 默认采用 CMake 来编译 C++ 和 C 源码, 这个文件是 CMake 的配置文件.

在 app module 下, 多出了一个 cpp 的目录, 里面包含了一个 native-lib.cpp 的文件, 这是 Android Studio 生成的 C++ 示例文件.

Project 视图

那么真实的物理目录结构是什么样的呢? 我们可以来看一下:

Screen Shot 2018-04-26 at 14.28.18

项链书多出了上面的三个文件:

  • CMakeLists.txt 位于 app/CMakeLists.txt
  • cpp 目录位于 src 下
  • 同时多出了一个 .externalNativeBuild 的文件夹, 里面包含着 Native 层的编译相关文件

示例代码

下面我们就来看一看示例代码中 Android 是如何引入 C++ 支持的.

首先来看我们的 Java 代码:

package com.dcr.hellomycpp;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.TextView;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();}

其中主要有两处变化, 我们现在关注后面的一处:

public native String stringFromJNI();

了解过 JNI 的应该知道, 这一句是定义了 Java 的 JNI 接口, 使用了 native 关键字, 来声明 Native 调用, 这个方法的实现将在 c/c++ 中完成.

接下来我们可以看一下这个 native 方法是如何实现的, native-lib.cpp 的实现如下:

#include #include extern "C" JNIEXPORT jstringJNICALLJava_com_dcr_hellomycpp_MainActivity_stringFromJNI(        JNIEnv *env,        jobject /* this */) {    std::string hello = "Hello from C++";    return env->NewStringUTF(hello.c_str());}

这段代码中的每个字段的具体含义, 我们在后面详细解释, 这里我们只要理解, 这就是 Java 中的 native 方法 stringFromJNI 的 C++ 实现.

CMakeLists.txt

我们只在源代码中引入 C++ 是还不够的, 我们的编译器还不能够正确的编译整个项目, 还需要我们前面提到过的 CMakeLists.txt 文件.

CMakeLists.txt 文件的内容如下所示:

# For more information about using CMake with Android Studio, read the# documentation: https://d.android.com/studio/projects/add-native-code.html# Sets the minimum version of CMake required to build the native library.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} )

这段代码中有三个主要部分: add_library, find_librarytarget_link_libraries.

add_library
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 )

add_library 传入三个参数:

  • 设置所引入的库的名称:

    这里库的名称为 native-lib, 那么我们在 Java 中引入 library 时所对应的代码段为:

    static {    System.loadLibrary("native-lib");}
  • 设置库的引入方式, 有两种方式, 静态 (STATIC) 和动态 (SHARED).

  • 提供源文件的相对路径: src/main/cpp/native-lib.cpp, 如果需要添加多个文件, 那么在这里添加.

find_library

find_library 用来添加一些编译本地库时需要依赖的一些库, 由于 CMake 已经知道系统库的路径 所以我们这里只是指定使用 log 库, 然后起了一个别名 log-lib 方便使用, log 库是 NDK 为我们提供的调试时打印 log 日志的库.

target_link_libraries

关联我们的库和第三方库或者系统库, 这里我们把我们的库和 log 库关联起来.

build.gradle

我们还需要在 gradel 中引入相关配置. 使用 CMake 配置需要在 Gradle 的两处引入 externalNativeBuild 语句块

  1. 在 android 语句块中, 引入 externalNativeBuild, 用来指定 CMakeLists.txt 的位置.

    externalNativeBuild {    cmake {        path "CMakeLists.txt"    }}
  2. 在 defaultConfig 中引入 externalNativeBuild, 用来指定额外的参数.

    externalNativeBuild {        cmake {            cppFlags ""            abiFilters "armeabi"        }}

运行结果

OK, 现在, 我们已经分析了整个项目的结构和配置, 现在让我们运行一下, 看一下结果吧:

device-2018-04-27-101830

如果我们分析 apk 文件我们会看到 apk 中包含了 .so 动态链接库.

Screen Shot 2018-04-27 at 10.21.22

更多相关文章

  1. Android之Android(安卓)Studio JNI
  2. Android(安卓)studio的NDK配置
  3. Android(安卓)指纹识别开发实例
  4. Android(安卓)Service生命周期及用法
  5. ubuntu14.04下搭建Android编译环境
  6. [Android(安卓)API学习]Data Storage胡乱翻译(1)
  7. Android(安卓)Studio启动崩溃的问题:Start Failed Internal error
  8. Google_android_JNI使用方法
  9. WebView:Android-H5交互

随机推荐

  1. Android学习笔记4——Activity的生命周期
  2. android http json请求3种不同写法
  3. Android使用ksoap2连接webserver(JAX-WS)
  4. android获取屏幕的宽度和高度
  5. [置顶] Android(安卓)按钮点击两次触发不
  6. maven android
  7. android横竖屏显示
  8. 整理出15个Android很有用的代码片段(技巧
  9. Android---58---初学GPS定位
  10. android坐标