解析android framework下利用app_process来调用java写的命令及示例
解析android framework下利用app_process来调用java写的命令及示例
在android SDK的framework/base/cmds目录下了,有不少目录,这些目的最终都是build出一个bin文件,再存放到/system/bin目录下,对于C/CPP写的命令,我们还是比较好理解的,都有一个main函数作为入口,但是在cmds目录下还有一些原生代码是java的,比如input、settings,那么这种类型的命令是怎么实现的呢?
笔者研习了原生的命令实现,写了一个demo,抛砖引玉吧!暂时叫strong吧!我们都知道java写的文件最后都是编译成了class文件,java类里面也有很多接口,在android平台上cmds目录下的各模块的java文件都实现了一个共同的方法,还是叫main(),真是情有独钟啊!当然从技术角度看叫其他名字也是可以的。那我们就简单实现以下这个class吧!如下:
virtual void onVmCreated(JNIEnv* env) { if (mClassName == NULL) { return; // Zygote. Nothing to do here. } /* * This is a little awkward because the JNI FindClass call uses the * class loader associated with the native method we're executing in. * If called in onStarted (from RuntimeInit.finishInit because we're * launching "am", for example), FindClass would see that we're calling * from a boot class' native method, and so wouldn't look for the class * we're trying to look up in CLASSPATH. Unfortunately it needs to, * because the "am" classes are not boot classes. * * The easiest fix is to call FindClass here, early on before we start * executing boot class Java code and thereby deny ourselves access to * non-boot classes. */ char* slashClassName = toSlashClassName(mClassName); mClass = env->FindClass(slashClassName); if (mClass == NULL) { ALOGE("ERROR: could not find class '%s'\n", mClassName); } free(slashClassName); mClass = reinterpret_cast<jclass>(env->NewGlobalRef(mClass)); } virtual void onStarted() { sp<ProcessState> proc = ProcessState::self(); ALOGV("App process: starting thread pool.\n"); proc->startThreadPool(); AndroidRuntime* ar = AndroidRuntime::getRuntime(); ar->callMain(mClassName, mClass, mArgC, mArgV); IPCThreadState::self()->stopProcess(); }if (className) { // Remainder of args get passed to startup class main() runtime.mClassName = className; runtime.mArgC = argc - i; runtime.mArgV = argv + i; runtime.start("com.android.internal.os.RuntimeInit", application ? "application" : "tool"); }Android平台提供的app_process,还是相当不错的,比较实用,利用好app_process还是可以写成很多供我们自己开发、测试、定制一些特殊的程序,给开发带来了很大的便利。