Unity调用Android aar实现Native崩溃
知识记录
- 使用Android Studio生成aar
- 在Android里实现Native层崩溃
- Unity中调用Android aar中的方法
Android Studio生成aar
1. 新建Native C++项目
2. 新建Android Module
在Porject模式的项目中,新建Module-Android Library
3. 在对应Module下新建Java Class
利用Android Studio的提示生成一个对应的JNI代码(在后面的步骤中可以参考,适用于不会写JNI的小白)
实现Native崩溃
1.利用Android Studio自动生成JNI的相关代码
在main目录下新建JNI Folder
在JNI目录下新建CMakeLists.txt,拷贝如下内容(记得修改Project的内容project(“crashlibrary”))
# 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.10.2)
# Declares and names the project.
project("crashlibrary")
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
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 )
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
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 )
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib} )
在JNI目录下新建Native-lib.cpp,可以参考系统生成的JNI代码定义自己的JNI代码,并引入Jni.h的头文件。
#include "XXX/XXX/jni.h"//这里修改成自己的jni地址
extern "C"
JNIEXPORT jint JNICALL
Java_com_florence_mylibrary_MyClass_MyCrash(JNIEnv *env, jclass clazz) {
// TODO: implement MyCrash()
}
利用指针地址错误制造Crash
修改build.gradle的内容
2.编译Aar
在Unity中调用aar中的方法
在Unity中添加aar,并在脚本中调用aar。
void OnGUI()
{
if (GUI.Button(new Rect(100,300, 300, 80), "<size=30>Make Crash</size>"))
{
androidJavaObject = new AndroidJavaObject("com.florence.mylibrary.MyClass");
androidJavaObject.CallStatic<int>("MyCrash");
}
}
生成Android APK,在手机运行点击Make Crash按钮,触发native崩溃。
参考链接
- 关于如何修改build.gradle的文件:https://blog.csdn.net/a673544319/article/details/103530401
- 在Unity里面调用Java的方法:https://www.cnblogs.com/ezhar/p/12883771.html
- 触发Android Crash:https://blog.csdn.net/ta893115871/article/details/108991277
- 关于AndroidJavaObject的使用:https://blog.csdn.net/final5788/article/details/96596679