欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AndroidStudio编译so库

程序员文章站 2022-03-03 22:01:13
步骤1.新建工程com.example.jnitest2.新建JniTest.java (MainActivity同级目录下)package com.example.jnitest;public class JniTest { static { System.loadLibrary("JniTest"); } public native static String getString();}3.Build->Make Project,在app的b...

步骤

1.新建工程com.example.jnitest

2.新建JniTest.java (MainActivity同级目录下)

package com.example.jnitest;

public class JniTest {
    static {
        System.loadLibrary("JniTest");
    }
    public native static String getString();
}

3.Build->Make Project,在app的build目录生成.class文件

JniTest\app\build\intermediates\javac\debug\classes>

4.在步骤3目录下,运行javah命令生成.h文件

javah -jni -classpath . com.example.jnitest.JniTest

5.在app/src/main目录下新建一个jni文件夹

6.将生成的.h文件拷贝到步骤5中jni文件夹

7.在jni目录下,新建c/c++source file,如main.c,并实现.h中方法

#include "jni.h"
#include "com_example_jnitest_JniTest.h"

JNIEXPORT jstring JNICALL Java_com_example_jnitest_JniTest_getString(JNIEnv *env, jclass jz){
  return (*env)->NewStringUTF(env,"this is the first time for me to use jni");
}

8.在jni目录下,新建Android.mk和Application.mk文件

  • Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

LOCAL_MODULE := JniTest
LOCAL_SRC_FILES := main.c
include $(BUILD_SHARED_LIBRARY)
  • Application.mk
APP_ABI := all

9.在jni目录下,运行命令ndk-build(需要将其加入到系统环境变量),即可在src/main/libs目录下生成so

ndk-build

10.在build.gradle中添加字段

android {
    ...
    sourceSets {
        main() {
            jniLibs.srcDirs = ['src/main/libs']
            jni.srcDirs = [] //屏蔽掉默认的jni编译生成过程
        }
    }
}

11.在MainActivity中调用

public class MainActivity extends AppCompatActivity {
    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView = findViewById(R.id.txt);
    }

    public void btnClick(View v){
        mTextView.setText(JniTest.getString());
    }
}

12.整个工程截图

AndroidStudio编译so库

参考链接

https://blog.csdn.net/leilifengxingmw/article/details/71598687

本文地址:https://blog.csdn.net/robothj/article/details/107374692

相关标签: 逆向