JNI(Cmake version) with Androidstudio for MAC

CMake is a cross-platform installation and compilation tool

New version of the way, mainly rely on cmakelists. TXT for development configuration

@[toc]

First, create a blank AndroidStudio project

Create a new AndroidStudio blank project and define jni native methods in MainActivity.

So GetHell’s method is going to explode and I’m not going to do it yet

public class MainActivity extends AppCompatActivity { static { System.loadLibrary("DemoTest"); } public native String GetHell(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toast.makeText(this, GetHell(), Toast.LENGTH_SHORT).show(); }}Copy the code

Configure the Cmake environment

Define the cmakelists. TXT configuration path under app/build.gradle/ Android

externalNativeBuild {
        cmake {
            path 'src/main/cpp/CMakeLists.txt'
        }
    }
Copy the code

Then create cmakelists.txt in SRC /main/ CPP /

Here we define the packaged so file as DemoTest and the JNI entry file as jni.cpp

Cmake_minimum_required (VERSION 3.4.1) set(LOCAL_MODULE DemoTest) # Specify the name of so that you will generate. add_library(${LOCAL_MODULE} SHARED # Following , the same as LOCAL_SRC_FILES in Android.mk JNI.cpp ) target_link_libraries(${LOCAL_MODULE} # Link the other so(dll). log )Copy the code

3. Deal with the native part

Create jni.cpp at SRC /main/ CPP /

Extern "C" JNIEXPORT jstring JNICALL Java_test(JNIEnv *env, jobject thiz) {}Copy the code

Right-click on MainActivity’s native method to generate the corresponding method

And then I can delete the top two lines

This is done, click run successfully below

In addition, we can also choose native C++ to run directly when creating a new AndroidStudio project

The demo address