1. 程式人生 > >引入第三方so庫

引入第三方so庫

1.生成so庫

2.把生成的so庫複製到專案libs目錄資料夾 3.修改專案build.gradle檔案
android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.example.administrator.aslibtest1"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags "-frtti -fexceptions"
            }
        }
        //如果需要指定開發平臺 如:
        /*ndk {
            abiFilters "armeabi","x86"
        }*/
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
    // 引入第三方庫,在app.gralde中的android目錄下
    sourceSets.main {
        jniLibs.srcDirs = ['libs']
        jni.srcDirs = []
    }
}
4.修改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)

find_library( # Sets the name of the path variable.
              log-lib
              log )

#設定so庫路徑
set(my_lib_path ${CMAKE_SOURCE_DIR}/libs)
#講第三方庫作為動態庫引用
add_library( native-lib
          SHARED
          IMPORTED )
#指名第三方庫的絕對路徑
set_target_properties( native-lib
                    PROPERTIES IMPORTED_LOCATION
                    ${my_lib_path}/${ANDROID_ABI}/libnative-lib.so )

add_library( # Sets the name of the library.
            libTest
            SHARED
            src/main/cpp/native-lib.c )

target_link_libraries( # Specifies the target library.
                      libTest
                      native-lib
                      ${log-lib} )
5.新增標頭檔案


6.觸發JNI呼叫

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
        System.loadLibrary("libTest");
    }

    @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(99,66));//165
    }

    /**
    * A native method that is implemented by the 'native-lib' native library,
    * which is packaged with this application.
    */
    public native int stringFromJNI(int a,int b);
}