This article is from: 103Style blog

This section uses Android Studio 3.4.2 as an example

Summary of NDK development articles


directory

  • Environment configuration
  • Create a new project that supports C/C++
  • Add C/C++ code to an existing project
  • Refer to the article

Environment configuration

  • Download and install Android Studio
  • configurationNDKThe environment
    • Start theAndroid Studio.
    • Figure below: in the interfaceConfigureIn the openSettingsInterface.
    • As shown below: inThe upper left cornerInput box inputsdk– > clickAndroid SDK– > clickSDK Tools→ Then check the boxLLDB,CMake,NDK→ And clickOK→ Click in the pop-up boxOK.
    • After the download and installation is complete, restart Android Studio.

Create a new project that supports C/C++

  • On the Android Studio screen, click Start a New Android Studio Project
  • As shown in the following figure, select from the pop-up interfaceNative C++And then clickNext.
  • Click directly on the new screenNext, or modifyName.Package name , Save locationThe values;
  • Click Finish on the new screen.

Android Studio will generate a template project for us that we can run directly and will display Hello from C++ upon launch.


Support C/C++ project file introduction

Open the Project pane from the left side of Android Studio and select Android View as shown below:

All we have to worry about is the following files highlighted in the red box above:

  • MainActivity: Applied view interface, loaded a namednative-libLibrary, defines anativeThe method ofstringFromJNIAnd thenstringFromJNIThe returned value is set toTextViewOn.
    public class MainActivity extends AppCompatActivity {
        static {
            System.loadLibrary("native-lib");
        }
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            ...
            tv.setText(stringFromJNI());
        }
        public native String stringFromJNI();
    }
    Copy the code
  • CMakeLists.txt: CMake build script.
     Set the lowest version of CMakeCmake_minimum_required (VERSION 3.4.1 track)Add a source file or library
    add_library(
            native-lib The name of the library
            SHARED Type of library
            native-lib.cpp) # library source file
    # reference the NDK library log named log-lib
    find_library(
            log-lib The library path corresponds to the variable name
            log) Library name in # NDK
    Make sure the log library can be used in native lib
    target_link_libraries(
            native-lib 
            ${log-lib})
    Copy the code
  • native-lib.cpp: sample C++ source file, locatedsrc/main/cpp/Directory.
    #include <jni.h>
    #include <string>
    
    extern "C"JNIEXPORT jString JNICALL // Name of the c method corresponding to the stringFromJNI method in MainActivity Java_com_lxk_myapplication_MainActivity_stringFromJNI( JNIEnv *env, jobject ) { std::string hello ="Hello from C++";
        return env->NewStringUTF(hello.c_str());
    }
    Copy the code
  • build.gradle: build file
    android {
        ...
        defaultConfig {
            ...
            externalNativeBuild {
                cmake {
                    cppFlags ""
                }
            }
        }
        externalNativeBuild {
            cmake {
                path "src/main/cpp/CMakeLists.txt"// Build script path version"3.10.2"//CMake version}}}Copy the code

If just run the Project, click on the left side of the Project pane and select the Project view, will be in the app/build/intermediates/cmake/debug/armeabi – v7a/generate a libnative – lib. So file.

CMake uses the lib library name. So specification to name the library file, which is the native lib we defined. However, when we load in Java code, we use the library name we defined, native-lib.

static {
    System.loadLibrary("native-lib");
}
Copy the code

Add C/C++ code to an existing project

To add or import native code to an existing Android Studio project, follow this basic process:

  • Create a new source file and add it to your Android Studio project, skipping this step if you already have native code or want to import a precompiled native library.
  • Create a CMake compilation scriptTo informCMakeHow to compile the original source file into the library. You also need this compilation script if you import and associate a precompiled library or platform library. If an existing native library already existsCMakeLists.txtCompile the script, or usendk-buildAnd containAndroid.mkIf the script is compiled, skip this step.
  • Provide a path to the CMake or dk-build script fileThat will beGradleAssociate with native libraries.GradleUse the compile script to import the source code into yourAndroid StudioThe project and the native library (.soFile) to packAPKIn the.
Recreate a Basic Activity project.

Create a new source file
  • Open the Project menu from the left and select the Project view from the drop-down menu.
  • Right click on itapp/src/Under themainDirectory, and then selectNew > DirectoryEnter a name for the directory (for examplecpp) and clickOK.
  • Right click on the directory you just created and selectNew > C/C++ Source File, enter a name, for examplehello-ndkIf you want to create a header file, check itCreate an associated headerCheck box, clickOK.
Create the CMake build script

If your original source file does not already have a CMake build script, you will need to create one yourself and include the appropriate CMake command.

It must be named cmakelists.txt.

  • Right click on app, then select New > File, enter cmakelists.txt as the File name and click OK.
  • Add commands toCMakeLists.txt
    Cmake_minimum_required (VERSION 3.4.1) add_library(hello-ndk SHARED SRC /main/ CPP /hello-ndk.cpp)Copy the code
  • useadd_library()To yourCMakeWhen the build script adds a source file or library,Android StudioIt will also be available after you synchronize the projectProjectView to display the associated header files. But just to make sureCMakeYou can locate your header files at compile time that you need to placeinclude_directories()Command add toCMakeBuild script and specify the path to the header:
    add_library(...)
    
    include_directories(src/main/cpp/include/)
    Copy the code
  • addNDK API.Android NDKProvides a set of practical nativeAPIAnd the library. willfind_library()Command to add to yourCMakeBuild scripts to locateNDKLibrary. In order toAndroid specific logging support libraryFor example, to ensure that your native library can be inlogThe library calls functions that you need to useCMakeIn the build scripttarget_link_libraries()Command association library:
    add_library(...)
    
    find_library( log-lib The variable name of the library path
                  log ) The corresponding library name
    
    Associate pre-built libraries with your own native libraries
    target_link_libraries( hello-ndk
                           ${log-lib} )
    Copy the code
Associate Gradle with your native library

To associate Gradle with your native library, you need to provide a path to a CMake or nk-build script file. As you build your application, Gradle runs CMake or NdK-build as dependencies and packages the shared libraries into your APK.

  • Click on theAndroid StudioThe left side menuProjectAnd selectAndroidThe view. Click the second option in the pop-up menuLink C++ Project with Gradle, as shown in Figure 1, click the folder, clickAndroid StudioThe icon’s buttons can be located in the project root directory and then configured as shown in Figure 2CMakeLists.txtTo the path, clickOK.

  • thenappIn the directorybuild.gradleThe following code is automatically added to the file.
    externalNativeBuild {
        cmake {
            path file('CMakeLists.txt')}}Copy the code
Configuring the Javah Command Tool < Optional >

As shown below, press Ctrl + Alt + S to enter the Setting interface and click Tools → External Tools → + Configuration to add External Tools. The parameters are as follows:

Name :JavaH
Program:$JDKPath$/bin/javah
Parameters: -encoding UTF-8 -d ../cpp -jni $FileClass$
Working directory: $SourcepathEntry$\.. \javaCopy the code

Edit MainActivity

Add the following code to MainActivity:

public class MainActivity extends AppCompatActivity {
    static {
        System.loadLibrary("hello-ndk");
    }
    public native String helloNDK();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar); TextView show = findViewById(r.i.t.v_show); show.setText(helloNDK()); . }... }Copy the code
Modify content_main. XML

Modify content_main. XML and add android:id=”@+id/tv_show” to TextView

<? xml version="1.0" encoding="utf-8"? > <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android". > <TextView android:id="@+id/tv_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!". /> </android.support.constraint.ConstraintLayout>Copy the code
Generate.h headers < optional >

Right-click MainActivity and select the External Tools JavaH from the pop-up box. The com_example_myApplication_mainActivity. h file will be generated in the CPP directory, your file name may be different.

Edit the hello – the NDK. CPP

Change hello-ndk. CPP to the following code:

#include <jni.h>// Make sure the name here is the same as the name of the header you generated#include "com_example_myapplication_MainActivity.h" JNIEXPORT jstring JNICALL Java_com_example_myapplication_MainActivity_helloNDK (JNIEnv * env, jobject){return env ->NewStringUTF("Hello NDK");
}
Copy the code
To run the program

Click Rebuild Project in the top menu bar Build, then press Shirt + F10 to run the program, and the word “Hello NDK” will be displayed on the interface.


Refer to the article

  • The official NDK Starter Guide

The Demo address

If you like it, please give it a thumbs up.

The above


Scan the qr code below, follow my public account Android1024, click attention, don’t get lost.