版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/syusikoku/article/details/86604526
环境配置
为了工程不出现问题最好是新建项目的时候选择c++/c项目支持 (android studio创建项目)##
app/library module gradle 配置
apply plugin: 'com.android.library'
android {
defaultConfig {
externalNativeBuild {
cmake {
cppFlags ""
}
}
ndk {
ldLibs "log"//实现__android_log_print
abiFilters 'x86', 'armeabi-v7a'
}
}
externalNativeBuild {
cmake {
path "src/main/cpp/CMakeLists.txt"
}
}
}
src/main/cpp/CMakeList.txt 项目创建的时候会自动生成,如果没有从其它地方复制 , main/cpp目录不存在就自己创建
cmake_minimum_required(VERSION 3.4.1)
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
native-lib.cpp
)
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log )
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib} )
native-lib.cpp 选择cpp是因为了解这块,各选语言###
#include <jni.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <android/log.h>
using namespace std;
#define LOG_TAG "zzg-ndk"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
extern "C"
JNIEXPORT jboolean JNICALL
Java_com_example_zyframework_SDKApi_isExpired(JNIEnv *env, jobject jobj, jlong time) {
LOGE("native isExpret time = %lld ", time);
return (jboolean) b;
}
使用示例
1.数据传递
- java传递数据给c(包含对象)
- c传递数据给java(包含对象)
2.c调用java成员变量\方法\创建java层对象
3. static native 使用示例
3. static native 静态的native方法
c代码中调用java中的方法示例
java代码
public class SDKUtils {
public void setTag(String tag) {
Log.e("zzg-ndk", "setTag tag = " + tag);
}
public static native void updateTag(String key);
}
cpp代码
extern "C"
JNIEXPORT void JNICALL
Java_com_example_sdkjiagu_SDKUtils_updateTag(JNIEnv *env, jclass jcls, jstring key_) {
const char *key = env->GetStringUTFChars(key_, 0);
LOGE("native updateTag key = %s ", key);
env->ReleaseStringUTFChars(key_, key);
// 得到jobject不会走构造方法
jobject jobj = (*env).AllocObject(jcls);
jmethodID _mid = (*env).GetMethodID(jcls, "setTag", "(Ljava/lang/String;)V");
string t_new = "2019-01-18 23:59:59";
(*env).CallVoidMethod(jobj,_mid,env->NewStringUTF(t_new.c_str()));
}
辅助资料
ndk编译之后so的路径
F:\zyprojectspace\AsProjects\zzgapps\HelloNdkCpp\ZYFramework\build\intermediates\cmake\debug\obj\x86
方法的方法签名的查看
未完,待续