标签:
Java代码: public class MessageUtil { static{ System.loadLibrary("sms"); } public static native void showToast(Object context,String message); } jni代码: 文件 -- sms.h // // Created by Mrper on 2015/8/2. // #include <jni.h> #ifndef SENDER_SMS_H #define SENDER_SMS_H void showToast(JNIEnv *env,jclass clazz,jobject handler,jstring message); static jint registeNativeMethods(JNIEnv *env,const char* className,JNINativeMethod *methods,int numMethod); static jint registeNatives(JNIEnv *env); #endif //SENDER_SMS_H 文件 -- sms.cpp // // Created by Mrper on 2015/8/2. // #include "sms.h" #include <stdio.h> static JNINativeMethod nativeMethods[] = { { "showToast", "(Ljava/lang/Object;Ljava/lang/String;)V", (void*)showToast } }; void showToast(JNIEnv *env,jclass clazz,jobject handler,jstring message){ jclass cls_toast = env->FindClass("android/widget/Toast"); jmethodID mid_showToast = env->GetStaticMethodID( cls_toast, "makeText", "(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;" ); jobject obj_toast = env->CallStaticObjectMethod(cls_toast,mid_showToast,handler,message,1000); jmethodID mid_show = env->GetMethodID(cls_toast,"show","()V"); env->CallVoidMethod(obj_toast,mid_show); } static jint registeNativeMethods(JNIEnv *env,const char* className,JNINativeMethod *methods,int numMethod){ jclass clazz; clazz = env->FindClass(className); if (clazz == NULL) return JNI_FALSE; if (env->RegisterNatives(clazz,methods,numMethod) < 0){ return JNI_FALSE; } return JNI_TRUE; } static jint registeNatives(JNIEnv *env){ if (registeNativeMethods(env,"com/mrper/sender/MessageUtil",nativeMethods, sizeof(nativeMethods)/sizeof(nativeMethods[0]) ) != JNI_TRUE){ return JNI_FALSE; } return JNI_TRUE; } jint JNI_OnLoad(JavaVM *vm, void*reserved){ jint result = -1; JNIEnv *env; vm->GetEnv((void**)&env,JNI_VERSION_1_6); if (env == NULL){ goto fail; } if (registeNatives(env) != JNI_TRUE){ goto fail; } result = JNI_VERSION_1_6; fail: return result; }
标签:
原文地址:http://my.oschina.net/cse/blog/486745