AndroidStudio Ndk开发

https://blog.csdn.net/Young_Time/article/details/80346631

https://blog.csdn.net/yao_94/article/details/79151804

https://blog.csdn.net/u012737144/article/details/52943918

1.创建调用so的类JniTest.java  

package com.example.test; 
    public class JniTest {
        static {
            System.loadLibrary("JNIHello");
        }

        public static native String sayHello();
    }

2.创建.h文件
    cd 到java目录,在java统计目录创建jni文件夹

cd jni
javah -d ../jni com.example.test.JniTest

   在java同级目录内能看到jni文件夹和com_example_test_JniTest.h文件

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_example_test_JniTest */

#ifndef _Included_com_example_test_JniTest
#define _Included_com_example_test_JniTest
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_example_test_JniTest
 * Method:    sayHello
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_example_test_JniTest_sayHello
  (JNIEnv *, jclass);

#ifdef __cplusplus
}
#endif
#endif

  
3.创建c/c++实现代码
    创建JNIHello.cpp  


#include "com_example_test_JniTest.h"
#include <string>

JNIEXPORT jstring JNICALL Java_com_example_test_JniTest_sayHello
  (JNIEnv *env, jclass jls){
    
    std::string str_hello = "hello jni so";
    return env->NewStringUTF(str_hello.c_str());
  }

 

4.配置编译选项
    a.配置生成so的路径,在build.gradle  

sourceSets {    
main { jniLibs.srcDirs
= ['src/main/java/libs'] jni.srcDirs = []//['src/main/java/jni', 'src/main/jni/'] } }

    b.配置android.mk
       

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE := JNIHello
LOCAL_SRC_FILES := JNIHello.cpp
include $(BUILD_SHARED_LIBRARY)

# Android.mk
# https://developer.android.google.cn/ndk/guides/cpp-support#static_runtimes
# 可以边写多个模块
# include $(CLEAR_VARS)
# LOCAL_MODULE := JNIHello
# LOCAL_SRC_FILES := JNIHello.cpp
# include $(BUILD_SHARED_LIBRARY)


    c.配置application.mk
       

# 所有平台
APP_ABI := all

# https://developer.android.google.cn/ndk/guides/cpp-support
# 共享c++ stl
APP_STL := c++_shared


5.编译
 cd jni文件夹内部,set path="ndk路径";%path%

ndk-build


6.src/main/java/libs看到so

补充,下面的链接介绍了不需要编写android.mk和appliacation.mk文件,直接使用as编译so的方法

https://www.cnblogs.com/why168888/p/5592017.html

https://www.jianshu.com/p/464cd879eaba

新版的android studio在创建的时候可以选择c++模式支持,就会自动有so的代码框架:

 

posted @ 2019-07-30 10:58  _**  阅读(311)  评论(0编辑  收藏  举报