本文主要是介绍JNI实现动态加载AF打点,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
java代码
package com.example.myapplication;import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;import dalvik.system.DexClassLoader;/*** @Author: ddup* @Date: 2024/6/27* @Description: java调C代码*/
public class Trace {static {System.loadLibrary("Test"); //加载动态链接库}/*** 让C代码做加法运算,把结果返回* 场景:大量运算,编解码之类的,需要性能很高的情况下,可以用C代码** @param x* @param y* @return*/public native int add(int x, int y);/*** 从java传入字符串,C代码进行拼接** @param s I am from java* @return I am from java and I am from c*/public native String sayHello(String s);/*** 让C代码给每个元素都加上10** @param intArray* @return*/public native int[] increaseArrayEles(int[] intArray);/*** 应用:检查密码是否正确,如果正确返回200,否则返回400** @param pwd* @return*/public native int checkPwd(String pwd);public native void invokeLoadClass();public native void loadOption(Context context);public native void copyDex(Context context, AssetManager manager, String name, String path);public void getLaoder(Context context) {ClassLoader loader = Thread.currentThread().getContextClassLoader();try {Class loadedClass = loader.loadClass("java/lang/String");Method method = loadedClass.getMethod("length");int length = (int) method.invoke("sssssssssssssssss");Log.e("xxx", length + "");} catch (ClassNotFoundException e) {throw new RuntimeException(e);} catch (NoSuchMethodException e) {throw new RuntimeException(e);} catch (InvocationTargetException e) {throw new RuntimeException(e);} catch (IllegalAccessException e) {throw new RuntimeException(e);}}public void laodClassByDexClassLoader(Context context) {// 指定dex文件所在的目录和缓存目录File dexDir = new File("/storage/emulated/0/Android/data/com.pn.cal/files/out.dex");File optimizedDexDir = new File("/storage/emulated/0/Android/data/com.pn.cal/files/output");// 创建DexClassLoader实例DexClassLoader dexClassLoader = new DexClassLoader(dexDir.getAbsolutePath(),optimizedDexDir.getAbsolutePath(),null,context.getClassLoader() // 使用当前类加载器作为父加载器);// 使用DexClassLoader加载类try {Class<?> clazz = dexClassLoader.loadClass("com.example.myapplication.Heave");// 获取类实例,调用方法等...Object myClassInstance = clazz.newInstance();Method method = clazz.getMethod("hello",String.class);String str = (String) method.invoke(myClassInstance, "zhougang");Log.e("xxx",str);Method method2 = clazz.getMethod("initAF",Context.class);method2.invoke(myClassInstance, context);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();} catch (NoSuchMethodException e) {throw new RuntimeException(e);} catch (InvocationTargetException e) {throw new RuntimeException(e);}}
}
C代码
//
// Created by ddup on 2024/6/27.
//
#include "string.h"
#include <stdlib.h>#include <android/log.h>
#include <jni.h>#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>AAssetManager *mgr = NULL;#define TAG "ddup"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__) // 定义LOGD类型
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__) // 定义LOGI类型
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG ,__VA_ARGS__) // 定义LOGW类型
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG ,__VA_ARGS__) // 定义LOGE类型
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,TAG ,__VA_ARGS__) // 定义LOGF类型JNIEXPORT char *JNICALL
Java_com_example_MyClass_myMethod(JNIEnv*env,jobject obj, jstring jstr) {const char *cstr = (*env)->GetStringUTFChars(env, jstr,NULL);// 使用 cstr 进行操作,并获取结果(假设结果为 result)(*env)->ReleaseStringUTFChars(env, jstr, cstr);char *result = (char *) malloc(strlen(cstr) + 1);strcpy(result, cstr);return result;
}/*** jint:返回值* Java_全类名_方法名* JNIEnv *env*/
jint Java_com_example_myapplication_Trace_add(JNIEnv *env, jobject jobj, jint ji, jint jj) {int result = ji + jj;return result;
};/*** 从java传入字符串,C代码进行拼接** @param s I am from java* @return I am from java and I am from c
*/jstring Java_com_example_myapplication_Trace_sayHello(JNIEnv *env, jobject jobj, jstring jstring1) {char *fromJava = Java_com_example_MyClass_myMethod(env, jobj, jstring1);char *fromC = " and I am from C";
//拼接函数,拼接后得到的结果放到第一个参数里面strcat(fromJava, fromC);//把拼接的结果放在第一个参数里面
//jstring (*NewStringUTF)(JNIEnv*, const char*);LOGE("fromJava==%s\n", fromJava);return (*env)->NewStringUTF(env, fromJava);
};/*** 给每个元素加10* 场景:图片处理,颜色矩阵(就是数组),进行数组的处理*/
jintArray Java_com_example_myapplication_Trace_increaseArrayEles(JNIEnv *env, jobject jobj, jintArray jintArray1) {
//1.得到数组的长度
//jsize (*GetArrayLength)(JNIEnv*, jarray);jsize size = (*env)->GetArrayLength(env, jintArray1);
//2.得到数组的元素
// jint* (*GetIntArrayElements)(JNIEnv*, jintArray, jboolean*);jint *intArray = (*env)->GetIntArrayElements(env, jintArray1,JNI_FALSE);//这里传0 false表示 在同一份内存操作,不开辟新的内存
//3.遍历数组,给每个元素加10int i;for (i = 0; i < size; i++) {*(intArray + i) += 10;}
//4. 同步修改到 Java 层(*env)->ReleaseIntArrayElements(env, jintArray1, intArray, 0);
//5.返回结果return jintArray1;
};/*** 应用:检查密码是否正确,如果正确返回200,否则返回400*/
jint Java_com_example_myapplication_Trace_checkPwd(JNIEnv *env, jobject jobj, jstring jstring1) {
//假设服务器的密码是123456char *origin = "123456";char *fromUser = Java_com_example_MyClass_myMethod(env, jobj, jstring1);
//函数比较字符串是否相同int code = strcmp(origin, fromUser);LOGE("code==%d\n", code);if (code == 0) {return 200;} else {return 400;}
}JNIEXPORT void JNICALL
Java_com_example_myapplication_Trace_invokeLoadClass(JNIEnv *env, jobject obj) {// 获取当前线程的ClassLoaderjclass threadClass = (*env)->FindClass(env, "java/lang/Thread");jmethodID getClassLoaderMid = (*env)->GetStaticMethodID(env, threadClass, "currentThread","()Ljava/lang/Thread;");jmethodID getClassLoaderMid2 = (*env)->GetMethodID(env, threadClass, "getContextClassLoader","()Ljava/lang/ClassLoader;");
// jobject classLoaderObj = (*env)->CallStaticObjectMethod(env, threadClass, getClassLoaderMid);jobject classLoaderObj = (*env)->CallObjectMethod(env, (*env)->CallStaticObjectMethod(env,threadClass,getClassLoaderMid),getClassLoaderMid2);
// if (classLoaderObj == NULL) {
// classLoaderObj = (*env)->CallObjectMethod(env, (*env)->CallStaticObjectMethod(env, threadClass, getClassLoaderMid), getClassLoaderMid2);
// }// 通过反射获取ClassLoader的loadClass方法jclass classLoaderClass = (*env)->FindClass(env, "java/lang/ClassLoader");if (classLoaderClass != NULL) {LOGD("xxx classloader find");}jmethodID loadClassMid = (*env)->GetMethodID(env, classLoaderClass, "loadClass","(Ljava/lang/String;)Ljava/lang/Class;");if (loadClassMid != NULL) {LOGD("xxx loadClass method find");}// 反射调用loadClass方法加载类jstring classNameStr = (*env)->NewStringUTF(env, "java/lang/String"); // 替换为要加载的类的全限定名jclass clazz = (*env)->CallObjectMethod(env, classLoaderObj, loadClassMid, classNameStr);// 打印结果,验证是否成功加载类if (clazz != NULL) {LOGI("xxx Class loaded successfully\n");} else {LOGI("xxx Failed to load class\n");}
}JNIEXPORT void JNICALL
Java_com_example_myapplication_Trace_loadOption(JNIEnv *env, jobject obj, jobject context) {// 获取当前线程的ClassLoaderjclass threadClass = (*env)->FindClass(env, "java/lang/Thread");jmethodID thread_current_method_ID = (*env)->GetStaticMethodID(env, threadClass, "currentThread","()Ljava/lang/Thread;");jmethodID thread_get_contextclassLoader_method_ID = (*env)->GetMethodID(env, threadClass, "getContextClassLoader","()Ljava/lang/ClassLoader;");
// jobject classLoaderObj = (*env)->CallStaticObjectMethod(env, threadClass, getClassLoaderMid);jobject threadObj = (*env)->CallStaticObjectMethod(env,threadClass,thread_current_method_ID);jobject classLoaderObj = (*env)->CallObjectMethod(env,threadObj,thread_get_contextclassLoader_method_ID);// 通过反射获取ClassLoader的loadClass方法jclass classLoaderClass = (*env)->FindClass(env, "java/lang/ClassLoader");if (classLoaderClass != NULL) {LOGD("xxx classloader find");}jmethodID classLoader_loadClass_MethodID = (*env)->GetMethodID(env, classLoaderClass,"loadClass","(Ljava/lang/String;)Ljava/lang/Class;");if (classLoader_loadClass_MethodID != NULL) {LOGD("xxx loadClass method find");}// 反射调用loadClass方法加载类jstring classNameStr = (*env)->NewStringUTF(env,"com/example/myapplication/Heave"); // 替换为要加载的类的全限定名//执行classLoader的loadClass方法,传入一个参数:方法名,得到Clazzjclass heaven_clazz = (*env)->CallObjectMethod(env, classLoaderObj,classLoader_loadClass_MethodID, classNameStr);// 打印结果,验证是否成功加载类if (heaven_clazz != NULL) {LOGI("heave class loaded");} else {LOGI("heave class fail");}// 获取Example类的构造函数的IDjmethodID constructorMID = (*env)->GetMethodID(env, heaven_clazz, "<init>", "()V");if (constructorMID == NULL) {LOGI("heave construct class fail");return; // 构造函数未找到} else {LOGI("heave construct class success");}// 使用构造函数ID创建Example类的实例jobject exampleObj = (*env)->NewObject(env, heaven_clazz, constructorMID);if (exampleObj == NULL) {LOGI("create object fail");return; // 对象创建失败} else {LOGI("create object success");}//找到方法 hellojmethodID heave_class_hello_methodID = (*env)->GetMethodID(env, heaven_clazz, "hello","(Ljava/lang/String;)Ljava/lang/String;");if (heave_class_hello_methodID != NULL) {LOGI("heave hello method loaded");} else {LOGI("heave hello method fail");}jmethodID heave_class_initAF_methodID = (*env)->GetMethodID(env, heaven_clazz, "initAF","(Landroid/content/Context;)Ljava/lang/String;");if (heave_class_initAF_methodID != NULL) {LOGI("heave initAF method loaded");} else {LOGI("heave initAF method fail");}jstring helloStr = (*env)->NewStringUTF(env, "zhougang"); // 替换为要加载的类的全限定名// 调用hello方法(*env)->CallObjectMethod(env, exampleObj, heave_class_hello_methodID, helloStr);// 调用initAF方法(*env)->CallObjectMethod(env, exampleObj, heave_class_initAF_methodID, context);// 释放本地引用
// (*env)->DeleteLocalRef(env,heaven_clazz);
// (*env)->DeleteLocalRef(env,exampleObj);// jmethodID heave_class_initAF_methodID = (*env)->GetMethodID(env, heaven_clazz, "initAF","(Landroid/content/Context;)");//执行Heave的 initAF方法
// jobject hello = (*env)->CallObjectMethod(env, heaven_clazz, heave_class_initAF_methodID,helloStr);// Method method = loadedClass.getMethod("length");
//
// int length = (int)method.invoke("sssssssssssssssss");/**** 在JNI中,当我们使用GetFieldID/GetStaticFieldID或GetMethodID/GetStaticMethodID及定义JNINativeMethod等时,我们需要表示成员变量的类型,或函数传入参数或返回的类型。JNI把Field的类型,或函数传入参数或返回值的类型进行简写以char*的形式进行表示。对于成员变量,直接用java类型的简写表示成员变量的类型就可以比如:"I"表示该成员变量是Int类型"Ljava/lang/String;"表示该成员变量是String类型示例1:jfieldID str = (env)->GetFieldID(objectClass,"name","Ljava/lang/String;");jfieldID ival = (env)->GetFieldID(objectClass,"serial","I");对于成员函数,是以"(*)+"形式表示函数的有哪些传入参数,传入参数的类型,返回值的类型。"()" 中的字符表示传入参数,后面的则代表返回值。例如:"()V" 就表示void Func();"(II)V" 表示 void Func(int, int);"(Ljava/lang/String;Ljava/lang/String;)I".表示 int Func(String,String)*/}JNIEXPORT jstring JNICALL
Java_com_example_myapplication_MainActivity_mergeStrings(JNIEnv *env, jobject thiz, jstring string1,jstring string2) {const char *cStr1 = (*env)->GetStringUTFChars(env, string1, 0);const char *cStr2 = (*env)->GetStringUTFChars(env, string2, 0);// 合并字符串char *mergedString = strcat(cStr1, cStr2);return (*env)->NewStringUTF(env, mergedString);}JNIEXPORT void JNICALL
Java_com_example_myapplication_loadDex(JNIEnv *env, jobject thiz,jobject context,jstring dexpath) {
// const char *path = (*env)->GetStringUTFChars(env,dexpath,0);jclass stringClass = (*env)->FindClass(env,"java/lang/String");jclass dexClassLoaderClass = (*env)->FindClass(env,"dalvik/system/DexClassLoader");if(dexClassLoaderClass == NULL){LOGI("dexclassloaderclazz not find");}else{LOGI("dexclassloaderclazz find");}jmethodID dexClassLoaderConstructor = (*env)->GetMethodID(env,dexClassLoaderClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/ClassLoader;)V");jstring optDexDirStr = dexpath;//(*env)->NewStringUTF(env,path);jstring libDirStr = dexpath; //(*env)->NewStringUTF(env,path);jstring dexDirStr = dexpath;//(*env)->NewStringUTF(env,path);LOGI("%s", (*env)->GetStringUTFChars(env, optDexDirStr, 0));// 通过反射获取context.getClassLoader()jclass context_clazz = (*env)->FindClass(env, "android/content/Context");jmethodID context_getClassLoaderMethod_ID = (*env)->GetMethodID(env,context_clazz, "getClassLoader","()Ljava/lang/ClassLoader;");jclass classLoaderClazz = (*env)->FindClass(env, "java/lang/ClassLoader");jobject classLoaderObj = (*env)->CallObjectMethod(env,context,context_getClassLoaderMethod_ID);//创建DexClassLoader对象jobject dexClassLoaderObj = (*env)->NewObject(env,dexClassLoaderClass, dexClassLoaderConstructor, optDexDirStr, libDirStr, dexDirStr, classLoaderObj);if(dexClassLoaderObj == NULL){LOGI("dexcloassloader 没有成功");}else{LOGI("加载DexclassLoader成功");}// 反射调用loadClass方法加载类
// jstring classNameStr = (*env)->NewStringUTF(env,"com/example/myapplication/Heave"); // 替换为要加载的类的全限定名
// jmethodID classLoader_loadClass_MethodID = (*env)->GetMethodID(env, dexClassLoaderClass,"loadClass","(Ljava/lang/String;)Ljava/lang/Class;");
//
// //执行classLoader的loadClass方法,传入一个参数:方法名,得到Clazz
// jclass heaven_clazz = (*env)->CallObjectMethod(env, dexClassLoaderObj,classLoader_loadClass_MethodID, classNameStr);
//
// if(heaven_clazz == NULL){
// LOGI("找不到了 heaveClass ");
// }else{
// if(heaven_clazz == NULL){
// LOGI("找到了 heaveClass ");
// }
// }}JNIEXPORT void JNICALL
Java_com_example_myapplication_Trace_copyDex(JNIEnv *env, jobject thiz, jobject context,jobject assetManager, jstring assetName,jstring destPath) {const char *nativeAssetName = (*env)->GetStringUTFChars(env, assetName, 0);const char *nativeDestPath = (*env)->GetStringUTFChars(env, destPath, 0);LOGI("xxx fromJava==%s\n", nativeDestPath);LOGI("xxx fromJava==%s\n", nativeAssetName);AAssetManager *asMg = AAssetManager_fromJava(env, assetManager);AAsset *asset = AAssetManager_open(asMg, nativeAssetName, AASSET_MODE_UNKNOWN);if (asset == NULL) {LOGI("%s not found in asset", nativeAssetName);return;}int assetLength = AAsset_getLength(asset);char *assetBuffer = (char *) malloc(assetLength);memset(assetBuffer, 0x00, assetLength);int numBytesRead = AAsset_read(asset, assetBuffer, assetLength);LOGI("这一步");//合并字符串jstring sp= (*env)->NewStringUTF(env, "/");const char *spp = (*env)->GetStringUTFChars(env,sp,0);char *nativeDestPathNew = strcat(nativeDestPath,spp);char *mergedString = strcat(nativeDestPathNew,nativeAssetName);FILE *destFile = fopen(mergedString, "wb");if (destFile == NULL) {LOGE("Could not open file %s", nativeDestPath);free(assetBuffer);AAsset_close(asset);return;}fwrite(assetBuffer, 1, assetLength, destFile);fclose(destFile);free(assetBuffer);AAsset_close(asset);(*env)->ReleaseStringUTFChars(env, assetName, nativeAssetName);(*env)->ReleaseStringUTFChars(env, destPath, nativeDestPath);(*env)->ReleaseStringUTFChars(env, sp, spp);LOGI("%s",mergedString);LOGI("xxx 拷贝成功");jstring result= (*env)->NewStringUTF(env, mergedString);Java_com_example_myapplication_loadDex(env,thiz,context,destPath);}
使用 >dx --dex --min-sdk-version=26 --output=C:\Users\Administrator\Desktop\ss\out.dex C:\Users\Administrator\Desktop\ss 生成 out.dex,放在asset目录下,out.dex中主要包括的代码是一个操作类Heave.java,和appsflyer三方jar打包进去
Heave.java
package com.example.myapplication;import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Base64;
import android.util.Log;import com.appsflyer.AppsFlyerConversionListener;
import com.appsflyer.AppsFlyerLib;import org.json.JSONObject;import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;public class Heave {public String eString = "";public String status = "Organic";public Context context;/*** .class文件名中包含$ --> zzz$1.class* 这是因为在此类中有匿名类。 它们使用ClassName $ InnerClassName此命名约定进行编译。** @param context* @return*/public String initAF(Context context) {this.context = context;Log.e("xxx", "initAF from C");AppsFlyerLib appsFlyerLib = AppsFlyerLib.getInstance();appsFlyerLib.setDebugLog(true);Log.e("xxx","aaa");appsFlyerLib.init("2o5ebrDVwrE8RqB8DAdNo7",new MyAFListener(this), context);appsFlyerLib.start(context);Log.e("xxx","bbb");String appsflyer_id = appsFlyerLib.getAppsFlyerUID(context);HashMap<String, String> map = new HashMap<String, String>();map.put("appsflyer_id", appsflyer_id);map.put("token", "b801b903-4318-4bb0-9107-73efffdc7886");map.put("app_id", context.getPackageName());JSONObject jsonObject = new JSONObject(map);String afstr = jsonObject.toString();Log.e("xxx",afstr);eString = Base64.encodeToString(afstr.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT);return eString;}public void toNext(String status) {Log.e("xxx2",status);if ("Organic".equals(status)) {Intent intent = new Intent("android.intent.action.VIEW");intent.setAction("android.intent.action.main");context.startActivity(intent);((Activity)context).finish();} else {Intent intent = new Intent();intent.setAction("android.intent.action.protocol");intent.putExtra("data", "https://www.winclub.net?af=1199&af=" + eString);context.startActivity(intent);((Activity)context).finish();}}public String hello(String str) {Log.e("xxx", "hello from Heave");return "hello " + str;}}
这样就实现了在B包被打开之前是看不到任何AF相关的代码。
这篇关于JNI实现动态加载AF打点的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!