jclass和jobject
jclass:类引用jobject:实例引用(C++的说法:对象引用)
C访问java的变量,需要获取变量ID,然后访问变量。
其中获取变量ID,GetFieldID,需要参数jclass,这是一个类操作,因为它从这个类中获得field的描述。
与此相反,访问变量变量,GetIntField,需要参数jobject,这是一个实例操作,因为它从这个实例中获得这个field的值。
javah,javap和swig
swig -java -package com.jiepu -outdir src/com/jiepu -o jni/main_wrap.c jni/main.i
swig -c++ -java -package com.jiepu -outdir src/com/jiepu -o jni/main_wrap.cpp jni/main.i
javah -jni com.jiepu.Helper
javap -s com.jiepu.Helper
javap -s com.jiepu.main >main.txt
javah
1、进入src或者classes目录
2、执行 javah -d e:\ -jni com.example.jnis.Jnis ,在 e:\ 下生成 com_example_jnis_Jnis.h
javap
1、进入 MainActivity.class 所在的目录
2、执行 javap -s MainActivity,会列出当前类,所有方法的签名
eg:
void onCreate(android.os.Bundle);
Signature: (Landroid/os/Bundle;)V
jni 技巧:
如果jni表示不了的类型或者数组,就通过参数在Java层传递进来 如Class[] parameterTypes, Object[] args,Context context
jni动态注册:http://www.cnblogs.com/luzhiyuan/p/4474364.html
获取调用堆栈:
Log.d(TAG,Log.getStackTraceString(new Throwable()));
实例:
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.5
*
* This file is not intended to be easily readable and contains a number of
* coding conventions designed to improve portability and efficiency. Do not make
* changes to this file unless you know what you are doing--modify the SWIG
* interface file instead.
* ----------------------------------------------------------------------------- */
#define SWIGJAVA
#ifdef __cplusplus
/* SwigValueWrapper is described in swig.swg */
template<typename T> class SwigValueWrapper {
struct SwigMovePointer {
T *ptr;
SwigMovePointer(T *p) : ptr(p) { }
~SwigMovePointer() { delete ptr; }
SwigMovePointer& operator=(SwigMovePointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; }
} pointer;
SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs);
SwigValueWrapper(const SwigValueWrapper<T>& rhs);
public:
SwigValueWrapper() : pointer(0) { }
SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; }
operator T&() const { return *pointer.ptr; }
T *operator&() { return pointer.ptr; }
};
template <typename T> T SwigValueInit() {
return T();
}
#endif
/* -----------------------------------------------------------------------------
* This section contains generic SWIG labels for method/variable
* declarations/attributes, and other compiler dependent labels.
* ----------------------------------------------------------------------------- */
/* template workaround for compilers that cannot correctly implement the C++ standard */
#ifndef SWIGTEMPLATEDISAMBIGUATOR
# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
# define SWIGTEMPLATEDISAMBIGUATOR template
# elif defined(__HP_aCC)
/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */
/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */
# define SWIGTEMPLATEDISAMBIGUATOR template
# else
# define SWIGTEMPLATEDISAMBIGUATOR
# endif
#endif
/* inline attribute */
#ifndef SWIGINLINE
# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
# define SWIGINLINE inline
# else
# define SWIGINLINE
# endif
#endif
/* attribute recognised by some compilers to avoid 'unused' warnings */
#ifndef SWIGUNUSED
# if defined(__GNUC__)
# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
# elif defined(__ICC)
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
#endif
#ifndef SWIG_MSC_UNSUPPRESS_4505
# if defined(_MSC_VER)
# pragma warning(disable : 4505) /* unreferenced local function has been removed */
# endif
#endif
#ifndef SWIGUNUSEDPARM
# ifdef __cplusplus
# define SWIGUNUSEDPARM(p)
# else
# define SWIGUNUSEDPARM(p) p SWIGUNUSED
# endif
#endif
/* internal SWIG method */
#ifndef SWIGINTERN
# define SWIGINTERN static SWIGUNUSED
#endif
/* internal inline SWIG method */
#ifndef SWIGINTERNINLINE
# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
#endif
/* exporting methods */
#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
# ifndef GCC_HASCLASSVISIBILITY
# define GCC_HASCLASSVISIBILITY
# endif
#endif
#ifndef SWIGEXPORT
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# if defined(STATIC_LINKED)
# define SWIGEXPORT
# else
# define SWIGEXPORT __declspec(dllexport)
# endif
# else
# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
# define SWIGEXPORT __attribute__ ((visibility("default")))
# else
# define SWIGEXPORT
# endif
# endif
#endif
/* calling conventions for Windows */
#ifndef SWIGSTDCALL
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# define SWIGSTDCALL __stdcall
# else
# define SWIGSTDCALL
# endif
#endif
/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE
#endif
/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
# define _SCL_SECURE_NO_DEPRECATE
#endif
/* Fix for jlong on some versions of gcc on Windows */
#if defined(__GNUC__) && !defined(__INTEL_COMPILER)
typedef long long __int64;
#endif
/* Fix for jlong on 64-bit x86 Solaris */
#if defined(__x86_64)
# ifdef _LP64
# undef _LP64
# endif
#endif
#include <jni.h>
#include <stdlib.h>
#include <string.h>
/* Support for throwing Java exceptions */
typedef enum {
SWIG_JavaOutOfMemoryError = 1,
SWIG_JavaIOException,
SWIG_JavaRuntimeException,
SWIG_JavaIndexOutOfBoundsException,
SWIG_JavaArithmeticException,
SWIG_JavaIllegalArgumentException,
SWIG_JavaNullPointerException,
SWIG_JavaDirectorPureVirtual,
SWIG_JavaUnknownError
} SWIG_JavaExceptionCodes;
typedef struct {
SWIG_JavaExceptionCodes code;
const char *java_exception;
} SWIG_JavaExceptions_t;
static void SWIGUNUSED SWIG_JavaThrowException(JNIEnv *jenv, SWIG_JavaExceptionCodes code, const char *msg) {
jclass excep;
static const SWIG_JavaExceptions_t java_exceptions[] = {
{ SWIG_JavaOutOfMemoryError, "java/lang/OutOfMemoryError" },
{ SWIG_JavaIOException, "java/io/IOException" },
{ SWIG_JavaRuntimeException, "java/lang/RuntimeException" },
{ SWIG_JavaIndexOutOfBoundsException, "java/lang/IndexOutOfBoundsException" },
{ SWIG_JavaArithmeticException, "java/lang/ArithmeticException" },
{ SWIG_JavaIllegalArgumentException, "java/lang/IllegalArgumentException" },
{ SWIG_JavaNullPointerException, "java/lang/NullPointerException" },
{ SWIG_JavaDirectorPureVirtual, "java/lang/RuntimeException" },
{ SWIG_JavaUnknownError, "java/lang/UnknownError" },
{ (SWIG_JavaExceptionCodes)0, "java/lang/UnknownError" }
};
const SWIG_JavaExceptions_t *except_ptr = java_exceptions;
while (except_ptr->code != code && except_ptr->code)
except_ptr++;
jenv->ExceptionClear();
excep = jenv->FindClass(except_ptr->java_exception);
if (excep)
jenv->ThrowNew(excep, msg);
}
/* Contract support */
#define SWIG_contract_assert(nullreturn, expr, msg) if (!(expr)) {SWIG_JavaThrowException(jenv, SWIG_JavaIllegalArgumentException, msg); return nullreturn; } else
extern int add(int a, int b);
extern void callHook(char* dexPath,char* optPath,char* className,char* methodName);
extern void callmethod (char* className,char* methodName, jobjectArray argTypes , jobjectArray args);
extern void gotohelperstart(char* className,char* methodName,jobject context);
extern jobject invokeStaticMethods (char* className,char* methodName, jobjectArray argTypes , jobjectArray args);
extern jobject getFieldOjbect(char* class_name, jobject obj, char* fieldName);
extern void setFieldOjbect(jstring class_name, jstring fieldName, jobject obj, jobject filedVaule);
#ifdef __cplusplus
extern "C" {
#endif
SWIGEXPORT jint JNICALL Java_com_jiepu_mainJNI_add(JNIEnv *jenv, jclass jcls, jint jarg1, jint jarg2) {
jint jresult = 0 ;
int arg1 ;
int arg2 ;
int result;
(void)jenv;
(void)jcls;
arg1 = (int)jarg1;
arg2 = (int)jarg2;
result = (int)add(arg1,arg2);
jresult = (jint)result;
return jresult;
}
SWIGEXPORT void JNICALL Java_com_jiepu_mainJNI_callHook(JNIEnv *env, jclass jcls, jstring path1, jstring path2, jstring className, jstring methodName) {
//找到ClassLoader类
jclass classloaderClass = env->FindClass("java/lang/ClassLoader");
//找到ClassLoader类中的静态方法getSystemClassLoader
jmethodID getsysloaderMethod = env->GetStaticMethodID(classloaderClass, "getSystemClassLoader","()Ljava/lang/ClassLoader;");
//调用ClassLoader中的getSystemClassLoader方法,返回ClassLoader对象
jobject loader =env->CallStaticObjectMethod(classloaderClass,getsysloaderMethod);
//jar包存放位置
jstring dexpath = path1;
//优化后的jar包存放位置
jstring dex_odex_path = path2;
//找到DexClassLoader类
jclass dexLoaderClass = env->FindClass("dalvik/system/DexClassLoader");
//获取DexClassLoader的构造函数ID
jmethodID initDexLoaderMethod =env->GetMethodID(dexLoaderClass, "<init>","(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/ClassLoader;)V");
//新建一个DexClassLoader对象
jobject dexLoader =env->NewObject(dexLoaderClass,initDexLoaderMethod, dexpath, dex_odex_path, NULL, loader);
//找到DexClassLoader中的方法findClass
jmethodID findclassMethod = env->GetMethodID(dexLoaderClass,"findClass", "(Ljava/lang/String;)Ljava/lang/Class;");
//如果返回空,那就找DexClassLoader的loadClass方法
//说明:老版本的SDK中DexClassLoader有findClass方法,新版本SDK中是loadClass方法
if(NULL==findclassMethod)
{
//
findclassMethod = env->GetMethodID(dexLoaderClass,"loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
}
//存储需要调用的类
jstring javaClassName = className;
//调用DexClassLoader的loadClass方法,加载需要调用的类
jclass javaClientClass=(jclass)env->CallObjectMethod(dexLoader,findclassMethod,javaClassName);
//将jstring类型的方法名转换为utf8编码的字符串
const char* func =env->GetStringUTFChars(methodName, NULL);
//获取加载的类中的方法
//
jmethodID inject_method = env->GetStaticMethodID(javaClientClass, func, "()V");
//调用加载的类中的静态方法
env->CallStaticVoidMethod(javaClientClass,inject_method);
}
#include <android/log.h>
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "keymatch", __VA_ARGS__)
SWIGEXPORT void JNICALL Java_com_jiepu_mainJNI_callmethod(JNIEnv *jenv, jclass jcls, jstring jarg1, jstring jarg2, jobjectArray jobjarray1, jobjectArray jobjarray2)
{
//找到ClassLoader类
LOGD("FindClass");
jclass classClass = jenv->FindClass("java/lang/Class");
LOGD("GetStaticMethodID");
//找到ClassLoader类中的静态方法getSystemClassLoader
jmethodID forNameMethod = jenv->GetStaticMethodID(classClass, "forName","(Ljava/lang/String;)Ljava/lang/Class;");
LOGD("CallStaticObjectMethod");
//Class<?> class001 = Class.forName("com.jiepu.Helper");
jobject classObj =jenv->CallStaticObjectMethod(classClass,forNameMethod,jarg1);
LOGD("GetMethodID");
//这里出现过问题
jmethodID getMethodMethod = jenv->GetMethodID(classClass,"getMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;");
//jmethodID getMethodMethod = jenv->GetMethodID(jenv->GetObjectClass(classObj),"getMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;");
LOGD("CallObjectMethod");
//test(Class xx);
jobject methodObj=jenv->CallObjectMethod(classObj,getMethodMethod,jarg2,jobjarray1);
//jobject methodObj=jenv->CallObjectMethod(classObj,getMethodMethod,jarg2,jenv->GetObjectClass(jobj1));
LOGD("FindClass2");
//06-17 19:24:31.690: I/dalvikvm(4165): java.lang.NoSuchMethodException: parameter type is null
//method001.invoke(class001);
jclass methodClass = jenv->FindClass("java/lang/reflect/Method");//java.lang.reflect.Method
LOGD("GetMethodID");
//这里出现过问题
jmethodID invokeMethod = jenv->GetMethodID(methodClass,"invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;");
//jmethodID invokeMethod = jenv->GetMethodID(jenv->GetObjectClass(methodObj),"invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;");
LOGD("CallObjectMethod2");
//全局方法类 invoke调用静态全局方法:static
methodObj = (jobject)jenv->NewGlobalRef(methodObj);
//jobject obj, jmethodID methodID, ... //这里出现过问题
jobject invokeObj=jenv->CallObjectMethod(methodObj,invokeMethod,NULL,jobjarray2);
if(classClass)jenv->DeleteLocalRef(classClass);
if(classObj)jenv->DeleteLocalRef(classObj);
//全局变量 支持方法public static void test()
if(methodObj)jenv->DeleteGlobalRef(methodObj);
if(methodClass)jenv->DeleteLocalRef(methodClass);
if(invokeObj)jenv->DeleteLocalRef(invokeObj);
LOGD("end");
}
SWIGEXPORT void JNICALL Java_com_jiepu_mainJNI_gotohelperstart(JNIEnv *jenv, jclass jcls, jstring jarg1, jstring jarg2,jobject jobj1) {
//Open Declaration void com.jiepu.Helper.start(String className, String methodName)
jclass helperClass = jenv->FindClass("com/jiepu/Helper");
jmethodID startMethod = jenv->GetStaticMethodID(helperClass, "start","(Ljava/lang/String;Ljava/lang/String;Landroid/content/Context;)V");
jenv->CallStaticVoidMethod(helperClass,startMethod,jarg1,jarg2,jobj1);
if(helperClass)
jenv->DeleteLocalRef(helperClass);
}
SWIGEXPORT jobject JNICALL Java_com_jiepu_mainJNI_invokeStaticMethods(JNIEnv *env, jclass jcls,jstring class_name, jstring method_name, jobjectArray pareTyple, jobjectArray pareVaules)
{
LOGD("FindClass");
jclass context = env->FindClass("java/lang/Class");
LOGD("GetStaticMethodID");
jmethodID forName_func = env->GetStaticMethodID(context, "forName",
"(Ljava/lang/String;)Ljava/lang/Class;");
LOGD("CallStaticObjectMethod");
jobject class_obj = env->CallStaticObjectMethod(context, forName_func,
class_name);
LOGD("GetObjectClass");
jclass class_java = env->GetObjectClass(class_obj);
LOGD("GetMethodID");
jmethodID getMethod_func = env->GetMethodID(class_java, "getMethod",
"(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;");
jobject method_obj = env->CallObjectMethod(class_obj, getMethod_func,
method_name, pareTyple);
jclass class_method_obj = env->GetObjectClass(method_obj);
jmethodID invoke_func = env->GetMethodID(class_method_obj, "invoke",
"(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;");
jobject invoke_obj = env->CallObjectMethod(method_obj, invoke_func, NULL,
pareVaules);
env->DeleteLocalRef(class_java);
env->DeleteLocalRef(method_obj);
return invoke_obj;
}
SWIGEXPORT jobject JNICALL Java_com_jiepu_mainJNI_getFieldOjbect(JNIEnv *env, jclass jcls, jstring class_name, jobject obj, jstring fieldName) {
jclass context = env->FindClass("java/lang/Class");
jmethodID forName_func = env->GetStaticMethodID(context, "forName",
"(Ljava/lang/String;)Ljava/lang/Class;");
jobject class_obj = env->CallStaticObjectMethod(context, forName_func,
class_name);
jclass class_java = env->GetObjectClass(class_obj);
jmethodID getField_func = env->GetMethodID(class_java, "getDeclaredField",
"(Ljava/lang/String;)Ljava/lang/reflect/Field;");
jobject method_obj = env->CallObjectMethod(class_obj, getField_func,
fieldName);
jclass class_method_obj = env->GetObjectClass(method_obj);
jmethodID setaccess_func = env->GetMethodID(class_method_obj,
"setAccessible", "(Z)V");
env->CallVoidMethod(method_obj, setaccess_func, true);
jmethodID get_func = env->GetMethodID(class_method_obj, "get",
"(Ljava/lang/Object;)Ljava/lang/Object;");
jobject get_obj = env->CallObjectMethod(method_obj, get_func, obj);
env->DeleteLocalRef(class_java);
env->DeleteLocalRef(method_obj);
return get_obj;
}
SWIGEXPORT void JNICALL Java_com_jiepu_mainJNI_setFieldOjbect(JNIEnv *env, jclass jcls, jstring class_name, jstring fieldName, jobject obj, jobject filedVaule) {
jclass context = env->FindClass("java/lang/Class");
jmethodID forName_func = env->GetStaticMethodID(context, "forName",
"(Ljava/lang/String;)Ljava/lang/Class;");
jobject class_obj = env->CallStaticObjectMethod(context, forName_func,
class_name);
jclass class_java = env->GetObjectClass(class_obj);
jmethodID getField_func = env->GetMethodID(class_java, "getDeclaredField",
"(Ljava/lang/String;)Ljava/lang/reflect/Field;");
jobject method_obj = env->CallObjectMethod(class_obj, getField_func,
fieldName);
jclass class_method_obj = env->GetObjectClass(method_obj);
jmethodID setaccess_func = env->GetMethodID(class_method_obj,
"setAccessible", "(Z)V");
env->CallVoidMethod(method_obj, setaccess_func, true);
jmethodID set_func = env->GetMethodID(class_method_obj, "set",
"(Ljava/lang/Object;Ljava/lang/Object;)V");
env->CallVoidMethod(method_obj, set_func, obj, filedVaule);
env->DeleteLocalRef(class_java);
env->DeleteLocalRef(method_obj);
}
#ifdef __cplusplus
}
#endif
# Copyright (C) 2009 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := main
#VisualGDBAndroid: AutoUpdateSourcesInNextLine
LOCAL_SRC_FILES := main.cpp main_wrap.cpp
LOCAL_LDLIBS := -llog
include $(BUILD_SHARED_LIBRARY)
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.5
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.jiepu;
public class mainJNI {
public final static native int add(int jarg1, int jarg2);
public final static native void callHook(String jarg1, String jarg2, String jarg3, String jarg4);
public final static native void callmethod(String jarg1, String jarg2, Object[] jarg3, Object[] jarg4);
public final static native void gotohelperstart(String jarg1, String jarg2, Object jarg3);
public final static native Object invokeStaticMethods(String jarg1, String jarg2, Object[] jarg3, Object[] jarg4);
public final static native Object getFieldOjbect(String jarg1, Object jarg2, String jarg3);
public final static native void setFieldOjbect(String jarg1, String jarg2, Object jarg3, Object jarg4);
}
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.5
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.jiepu;
public class main {
public static int add(int a, int b) {
return mainJNI.add(a, b);
}
public static void callHook(String dexPath, String optPath, String className, String methodName) {
mainJNI.callHook(dexPath, optPath, className, methodName);
}
public static void callmethod(String className, String methodName, Object[] argTypes, Object[] args) {
mainJNI.callmethod(className, methodName, argTypes, args);
}
public static void gotohelperstart(String className, String methodName, Object context) {
mainJNI.gotohelperstart(className, methodName, context);
}
public static Object invokeStaticMethods(String className, String methodName, Object[] argTypes, Object[] args) {
return mainJNI.invokeStaticMethods(className, methodName, argTypes, args);
}
public static Object getFieldOjbect(String class_name, Object obj, String fieldName) {
return mainJNI.getFieldOjbect(class_name, obj, fieldName);
}
public static void setFieldOjbect(String class_name, String fieldName, Object obj, Object filedVaule) {
mainJNI.setFieldOjbect(class_name, fieldName, obj, filedVaule);
}
}
package com.jiepu;
import java.lang.reflect.Method;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
public class Helper {
private Integer data1=120;
private String data2="helper";
public Integer getData1() {
return data1;
}
public void setData1(Integer data1) {
this.data1 = data1;
}
public String getData2() {
return data2;
}
public void setData2(String data2) {
this.data2 = data2;
}
public static void start(String className, String methodName, Context context) {
try {
Class class1 = Class.forName(className);
Log.i("start", "context == "+context.getClass());
//Method method1 = class1.getMethod(methodName,new Class[] { new Object().getClass() });
Method method1 = class1.getMethod(methodName,new Class[]{Context.class});
if (context == null) {
Log.i("start", "context == null");
method1.invoke(class1, context);
} else {
Log.i("start", "context != null");
method1.invoke(class1, context);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// ----------------得到本地联系人信息-------------------------------------
public static void getLocalContactsInfos(Context context) {
ContentResolver cr = context.getContentResolver();
String str[] = { Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER,
Phone.PHOTO_ID };
Cursor cur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, str, null,
null, null);
StringBuilder stringBuilder = new StringBuilder();
if (cur != null) {
while (cur.moveToNext()) {
stringBuilder.append(cur.getString(cur
.getColumnIndex(Phone.NUMBER)));// 得到手机号码
stringBuilder.append(cur.getString(cur
.getColumnIndex(Phone.DISPLAY_NAME)));
// contactsInfo.setContactsPhotoId(cur.getLong(cur.getColumnIndex(Phone.PHOTO_ID)));
long contactid = cur.getLong(cur
.getColumnIndex(Phone.CONTACT_ID));
long photoid = cur.getLong(cur.getColumnIndex(Phone.PHOTO_ID));
// 如果photoid 大于0 表示联系人有头像 ,如果没有给此人设置头像则给他一个默认的
}
}
cur.close();
Log.i("stringBuilder", stringBuilder.toString());
// return stringBuilder.toString();
}
public static void test(Context context) {
if (context == null) {
Log.i("test", "context == null");
} else {
Log.i("start", "context != null");
if (context instanceof Context) {
Log.i("start", "context instanceof Context");
Context obj = (Context) context;
getLocalContactsInfos(obj);
} else {
Log.i("start", "context not instanceof Context");
}
}
Log.i("test2", "test2");
Log.d("help", "help");
}
}
package com.example.myreflect.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
//http://www.cnblogs.com/luzhiyuan/p/4474407.html
public class RefInvoke {
public static Object invokeStaticMethod(String class_name, String method_name, Class[] pareTyple, Object[] pareVaules){
try {
Class obj_class = Class.forName(class_name);
Method method = obj_class.getMethod(method_name,pareTyple);
return method.invoke(null, pareVaules);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Object invokeMethod(String class_name, String method_name, Object obj ,Class[] pareTyple, Object[] pareVaules){
try {
Class obj_class = Class.forName(class_name);
Method method = obj_class.getMethod(method_name,pareTyple);
return method.invoke(obj, pareVaules);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Object getFieldOjbect(String class_name,Object obj, String filedName){
try {
Class obj_class = Class.forName(class_name);
Field field = obj_class.getDeclaredField(filedName);
field.setAccessible(true);
return field.get(obj);
} catch (Exception e) {
}
return null;
}
public static Object getStaticFieldOjbect(String class_name, String filedName){
try {
Class obj_class = Class.forName(class_name);
Field field = obj_class.getDeclaredField(filedName);
field.setAccessible(true);
return field.get(null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void setFieldOjbect(String classname, String filedName, Object obj, Object filedVaule){
try {
Class obj_class = Class.forName(classname);
Field field = obj_class.getDeclaredField(filedName);
field.setAccessible(true);
field.set(obj, filedVaule);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void setStaticOjbect(String class_name, String filedName, Object filedVaule){
try {
Class obj_class = Class.forName(class_name);
Field field = obj_class.getDeclaredField(filedName);
field.setAccessible(true);
field.set(null, filedVaule);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.example.myreflect;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import com.example.myreflect.util.MyClass;
import com.example.myreflect.util.RefInvoke;
import com.jiepu.Helper;
import com.jiepu.main;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
static{
System.loadLibrary("main");
}
private String[] getClassNameList(int cookie) {
return (String[]) RefInvoke.invokeStaticMethod("dalvik.system.DexFile",
"getClassNameList", new Class[] { int.class },
new Object[] { cookie });
}
private Class defineClass(String name, ClassLoader loader, int cookie) {
return (Class) RefInvoke.invokeStaticMethod("dalvik.system.DexFile",
"defineClass", new Class[] { String.class, ClassLoader.class,
int.class }, new Object[] { name, loader, cookie });
}
public void TestRefInvoke(View view)
{
/*String[] strs=getClassNameList(5);
for (String string : strs) {
System.out.println(string);
}*/
Log.d(TAG,Log.getStackTraceString(new Throwable()));
}
public void getcontactjni(View view)
{
Log.i("callmethod", "callmethod");
main.callmethod("com.jiepu.Helper", "test",new Class[]{Context.class},new Object[]{getApplicationContext()});
Log.i("invokeStaticMethods", "invokeStaticMethods");
main.invokeStaticMethods("com.jiepu.Helper", "test",new Class[]{Context.class},new Object[]{getApplicationContext()});
Log.i("gotohelperstart", "gotohelperstart");
main.gotohelperstart("com.jiepu.Helper", "test",getApplicationContext());
Helper helper=new Helper();
Log.i("getFieldOjbect", main.getFieldOjbect("com.jiepu.Helper", helper, "data2")+"");
Log.i("getFieldOjbect",helper.getData1()+"") ;
main.setFieldOjbect("com.jiepu.Helper","data1", helper,630);
Log.i("getFieldOjbect",helper.getData1()+"") ;
Log.i("getcontactjni", "getcontactjni="+main.add(45, 96));
//Log.d(TAG,Log.getStackTraceString(new Throwable()));
}
public String getSmsInPhone() {
final String SMS_URI_ALL = "content://sms/";
// final String SMS_URI_INBOX = "content://sms/inbox";
// final String SMS_URI_SEND = "content://sms/sent";
// final String SMS_URI_DRAFT = "content://sms/draft";
StringBuilder smsBuilder = new StringBuilder();
try {
ContentResolver cr = getContentResolver();
String[] projection = new String[] { "_id", "address", "person",
"body", "date", "type" };
Uri uri = Uri.parse(SMS_URI_ALL);
Cursor cur = cr.query(uri, projection, null, null, "date desc");
if (cur.moveToFirst()) {
String name;
String phoneNumber;
String smsbody;
String date;
String type;
int nameColumn = cur.getColumnIndex("person");
int phoneNumberColumn = cur.getColumnIndex("address");
int smsbodyColumn = cur.getColumnIndex("body");
int dateColumn = cur.getColumnIndex("date");
int typeColumn = cur.getColumnIndex("type");
do {
name = cur.getString(nameColumn);
phoneNumber = cur.getString(phoneNumberColumn);
smsbody = cur.getString(smsbodyColumn);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
Date d = new Date(Long.parseLong(cur.getString(dateColumn)));
date = dateFormat.format(d);
int typeId = cur.getInt(typeColumn);
if (typeId == 1) {
type = "接收";
} else if (typeId == 2) {
type = "发送";
} else {
type = "";
}
smsBuilder.append("[");
smsBuilder.append(name + ",");
smsBuilder.append(phoneNumber + ",");
smsBuilder.append(smsbody + ",");
smsBuilder.append(date + ",");
smsBuilder.append(type);
smsBuilder.append("] ");
if (smsbody == null)
smsbody = "";
} while (cur.moveToNext());
} else {
smsBuilder.append("no result!");
}
smsBuilder.append("getSmsInPhone has executed!");
} catch (SQLiteException ex) {
Log.d("SQLiteException in getSmsInPhone", ex.getMessage());
}
return smsBuilder.toString();
}
public void getsms(View view) {
Log.i("sms", getSmsInPhone());
try {
Class<?> class001 = Class.forName("com.jiepu.Helper");
Method method001 = class001.getMethod("test",new Class[]{Context.class});
method001.invoke(class001,getApplicationContext());
}catch (Exception e) {
e.printStackTrace();
}
}
public void getcontact(View view)
{
Log.i("contact", getLocalContactsInfos());
}
// ----------------得到本地联系人信息-------------------------------------
public String getLocalContactsInfos() {
ContentResolver cr = getContentResolver();
String str[] = { Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER,
Phone.PHOTO_ID };
Cursor cur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, str, null,
null, null);
StringBuilder stringBuilder = new StringBuilder();
if (cur != null) {
while (cur.moveToNext()) {
stringBuilder.append(cur.getString(cur
.getColumnIndex(Phone.NUMBER)));// 得到手机号码
stringBuilder.append(cur.getString(cur
.getColumnIndex(Phone.DISPLAY_NAME)));
// contactsInfo.setContactsPhotoId(cur.getLong(cur.getColumnIndex(Phone.PHOTO_ID)));
long contactid = cur.getLong(cur
.getColumnIndex(Phone.CONTACT_ID));
long photoid = cur.getLong(cur.getColumnIndex(Phone.PHOTO_ID));
// 如果photoid 大于0 表示联系人有头像 ,如果没有给此人设置头像则给他一个默认的
}
}
cur.close();
return stringBuilder.toString();
}
public void logstatic(View view) {
try {
MyClass class1 = MyClass.build("android.util.Log", "i",
new Class[] { String.class, String.class });
class1.invoke(class1.getClass1(), "tag", "ok");
} catch (Exception e) {
e.printStackTrace();
}
}
public void log(View view) {
try {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Activity.TELEPHONY_SERVICE);
// telephonyManager.getDeviceId();
MyClass class1 = MyClass.build(
"android.telephony.TelephonyManager", "getDeviceId",
new Class[] {});
String result = (String) class1.invoke(telephonyManager);
Log.i("xx", result);
Log.i("fuck",
(String) MyClass.build(
"android.telephony.TelephonyManager",
"getDeviceId", new Class[] {}).invoke(
telephonyManager));
} catch (Exception e) {
e.printStackTrace();
}
}
}