android112 c代码打印日志,c反编译调用java

时间:2022-09-23 10:08:13

activity:

package com.itheima.ccalljava;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.view.Menu;
import android.view.View; public class MainActivity extends Activity {
static{
System.loadLibrary("hello");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} public void click(View v){
helloC();
} public native void helloC(); public void show(String message){
Builder builder = new Builder(this);
builder.setTitle("标题");
builder.setMessage(message);
builder.show();
}
}

hello.c反编译java类调用java

#include <jni.h>
#include <android/log.h>
#define LOG_TAG "System.out"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)//把后面的函数重命名成前面的函数,Android.mk添加LOCAL_LDLIBS += -llog
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) JNIEXPORT void JNICALL Java_com_itheima_ccalljava_MainActivity_helloC
(JNIEnv * env, jobject obj){//obj是MainActivity对象
LOGD("hello!");//打印日志,debug级别的
LOGI("hello!");////打印日志,info级别的
//jclass (*FindClass)(JNIEnv*, const char*);const char*第二个参数是字符串,返回字节码
//C语言用反射调用java代码
jclass clazz = (*env)->FindClass(env, "com/itheima/ccalljava/MainActivity");
//jmethodID (*GetMethodID)(JNIEnv*, jclass, const char*, const char*);返回方法的id
jmethodID methodID = (*env)->GetMethodID(env, clazz, "show", "(Ljava/lang/String;)V");//(Ljava/lang/String;)V是方法签名,java所有的方法都是有签名的,
//void (*CallVoidMethod)(JNIEnv*, jobject, jmethodID, ...);
(*env)->CallVoidMethod(env, obj, methodID, (*env)->NewStringUTF(env, "是时候再黑一波小志了"));//调用方法,obj是MainActivity对象,(*env)->NewStringUTF(env, "是时候再黑一波小志了")是把C的字符串转换为java的字符串。
}

android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_LDLIBS += -llog LOCAL_MODULE := hello
LOCAL_SRC_FILES := hello.c include $(BUILD_SHARED_LIBRARY)

Application.mk

APP_ABI := armeabi armeabi-v7a x86 //表示不同的平台

反射:

import java.lang.reflect.Method;

public class Demo {

    public static void main(String[] args) {
try {
//拿到类的字节码。Dialog是类名
Class clazz = Demo.class.getClassLoader().loadClass("Dialog");
//拿到方法,show是方法名,后面是方法的参数类型。
Method method = clazz.getDeclaredMethod("show", String.class);
//调用方法,因为method方法不是静态方法,所有clazz.newInstance()表示对象,后面是参数。
method.invoke(clazz.newInstance(), "好久没黑小志了"); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}