测试版本Android Q ,platform 8321
第一步
为了在framework层测试,我们需要在增加一个java类供apk调用
新建文件夹mytest
frameworks/base/core/java/android/mytest/
新建文件hellojni.java
frameworks/base/core/java/android/mytest/hellojni.java
内容如下:
package android.mytest;
public class hellojni{
public hellojni(){}
//声明native方法
public static native String displayString();
}
第二步
framework层新建cpp文件
通常情况下,jni存在的常见目录如下:
/framework/base/core/jni/
/framework/base/services/core/jni/
/framework/base/media/jni/
我们在/framework/base/core/jni/ 新建cpp文件
frameworks/base/core/jni/com_mid_test_hellojni.cpp:
//
// Created by Administrator on 2019/10/16 0016.
//
#include "jni.h"
#define LOG_TAG "HelloJNI"
#include
#include
#include "utils/misc.h"
#include
namespace android {
static jstring android_mytest_hellojni_displayString(JNIEnv *env, jclass clazz)
{
return env->NewStringUTF("Hello from JNI!");
}
/*
* JNI registration.
*/
static JNINativeMethod gMethods[] = {
/* name, signature, funcPtr */
{"displayString", "()Ljava/lang/String;",
(void*) android_mytest_hellojni_displayString
}
};
int register_android_mytest_hellojni(JNIEnv* env)
{ //此处的目录结构就是在Java framework层的文件目录,且必须一致
return jniRegisterNativeMethods(env, "android/mytest/hellojni",
gMethods, NELEM(gMethods));
}
}; // namespace android
com_mid_test_hellojni.cpp建好后需要动态加载:
--- a/frameworks/base/core/jni/AndroidRuntime.cpp
+++ b/frameworks/base/core/jni/AndroidRuntime.cpp
@@ -232,7 +232,7 @@ extern int register_com_android_internal_os_FuseAppLoop(JNIEnv* env);
extern int register_com_android_internal_os_Zygote(JNIEnv *env);
extern int register_com_android_internal_os_ZygoteInit(JNIEnv *env);
extern int register_com_android_internal_util_VirtualRefBasePtr(JNIEnv *env);
-
+extern int register_android_mytest_hellojni(JNIEnv* env); //kzh add for test hellojni
// Namespace for Android Runtime flags applied during boot time.
static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
// Feature flag name to enable/disable generational garbage collection in ART's
@@ -1606,6 +1606,7 @@ static const RegJNIRec gRegJNI[] = {
REG_JNI(register_com_android_internal_content_NativeLibraryHelper),
REG_JNI(register_com_android_internal_os_AtomicDirectory),
REG_JNI(register_com_android_internal_os_FuseAppLoop),
+ REG_JNI(register_android_mytest_hellojni), //kzh add for test hellojni
};
最后将com_mid_test_hellojni.cpp添加到makefile中build,
--- a/frameworks/base/core/jni/Android.bp
+++ b/frameworks/base/core/jni/Android.bp
@@ -214,6 +214,7 @@ cc_library_shared {
"fd_utils.cpp",
"android_hardware_input_InputWindowHandle.cpp",
"android_hardware_input_InputApplicationHandle.cpp",
+ "com_mid_test_hellojni.cpp",
],
include_dirs: [
测试验证,在任意一个system app中(第三方apk也可以,当然需要对应的jar包)测试
在某个Activity中加入一个log调用:
Log.d("jnitest",hellojni.displayString());
最后build整个project烧入设备开机验证。。。。。