android ndk开发

继上一文章的基础上做的,https://blog.csdn.net/u013519290/article/details/82365284

ndk版本首选项目最低版本进行,使用过高的版本做,低版本系统手机NDK兼容性不好,容易发生遇外的BUG

1、好首先在Library 项目目录下建立一个JNI Folder目录

android ndk开发_第1张图片

2、在Library项目中建立一个类文件,下面我以BLE蓝牙设备为例子,建立了一个BleJniLib文件,在类文件中写如下代码:

package com.example.facialmask;

public class BleJniLib {
    static {
        System.loadLibrary("BleJniLib");
    }
    public native static String sendBleData();
}

android ndk开发_第2张图片

3、当代码写完成后,可以在开发工具中Terminal中进入项目目录(必须是进入到项目中java目录 下),如图上所示,执行如下指令回车完成,这时候生成一个C语言c++的h文件,如图下所示

javah com.example.facialmask.BleJniLib

android ndk开发_第3张图片

经过上面的命令操作生成一个.h的文件(com_example_facialmask_BleJniLib.h),把这个文件放到JNI 目录下,如图下显示的cpp,在当前目前新建一个C\C++文件,写C\C++代码,如图下所示建立了一个main为名的(名字随便,根据C\C++规范命名),代码如下,返回一个" 58999测试 "字符串:

//
// Created by Administrator on 2018/9/4.
//
#include "com_example_facialmask_BleJniLib.h"
JNIEXPORT jstring JNICALL
Java_com_example_facialmask_BleJniLib_sendBleData(JNIEnv *env,jclass type){


    return env->NewStringUTF("58999测试");

}

android ndk开发_第4张图片

接下来在项目里写一个类实现,通过安卓sendBleData方法与C实现通信,这里取的名字为BleJniLib,要与build.gradle取的名字要一致

package com.example.facialmask;

public class BleJniLib {
    static {
        System.loadLibrary("BleJniLib");
    }
    public  native  String sendBleData();
}

android ndk开发_第5张图片

这里取的名字BleJniLib,与BleJniLib 类取的要一致

        ndk{
            moduleName "BleJniLib"
//            ldLibs "log","z","m"
//            abiFilters "armeabi","armeabi-v7a","x86"
        }

android ndk开发_第6张图片

需要在gradle.properties中添加android.useDeprecatedNdk=true

最后Rebuild Project或者如下所示选择重新构建c\c++代码

方式一

android ndk开发_第7张图片

方式二

android ndk开发_第8张图片

最后在项目根目录下的build\intermediates\ndk中找到生成的.so文件,把.so文件放到自己的项目中,或者把做好的SDK导入到自己的项目中使用,在我们的项目里可以这样调用,代码如下:

Toast.makeText(MainActivity.this, new BleJniLib().sendBleData(),Toast.LENGTH_SHORT).show() ;

如遇到下面报错信息

Error: Flag android.useDeprecatedNdk is no longer supported and will be removed in the next version of Android Studio.  Please switch to a supported build system.
Consider using CMake or ndk-build integration. For more information, go to:
 https://d.android.com/r/studio-ui/add-native-code.html#ndkCompile
 To get started, you can use the sample ndk-build script the Android
 plugin generated for you at:
 D:\android\project\EquipmentBleDemo\agreementlibrary\build\intermediates\ndk\debug\Android.mk
Alternatively, you can use the experimental plugin:
 https://developer.android.com/r/tools/experimental-plugin.html
To continue using the deprecated NDK compile for another 60 days, set 
android.deprecatedNdkCompileLease=1536829387365 in gradle.properties

解决方案如下使用Cmake实现,在当前项目build.gradle里添加如下配制,同时在当前目录下建立一个CMakeLists.txt文件,要修改这个文件中3个地方,so名字以及.cpp代码文件路径:

  defaultConfig {
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        // 使用Cmake工具
        externalNativeBuild {
            cmake {
                cppFlags ""
//                abiFilters 'arm64-v8a','armeabi-v7a','x86','x86_64'
            }
        }

    }
// 配置CMakeLists.txt路径
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"   // 设置所要编写的c源码位置,以及编译后so文件的名字
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets { main { jni.srcDirs = ['src/main/jni', 'src/main/jni/'] } }

如图下所示

android ndk开发_第9张图片

CMakeLists.txt文件内容如下,设置so文件名称改成自己的项目so名称,设置这个so文件为共享改成自己的c/c++代码文件路径,制定目标库改成自己的so名称:

# 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.
#CMakeLists.txt
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.
            # 设置so文件名称.
             BleJniLib
             # Sets the library as a shared library.
             SHARED
             # 设置这个so文件为共享.
             # Provides a relative path to your source file(s).
             # 设置这个so文件为共享.
             src/main/jni/getBleData.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.
                       # 制定目标库.
                       BleJniLib
                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )

最后重新打包APP就可以使用了。

使用方式二、把生成的so文件和jar包放到新的项目libs中使用,同时在build.gradle文件中添加如下代码

sourceSets {
    main() {
        jniLibs.srcDirs = ['libs']
    }
}

android ndk开发_第10张图片

你可能感兴趣的:(android开发)