Native Method
- While a 100% pure Java solution is nice in principle, realistically, for an application, there are situations in which you will want to write or use code written in another language. Such code is usually called native code.
- There are three obvious reasons why that may be the right choice:
- You have substantial amounts of tested and debugged code available in that language. Porting the code to the Java programming language would be time consuming, and the resulting code would need to be tested and debugged again.
- Your application requires access to system features or devices, and using Java technology would be cumbersome at best, or impossible at worst.
- Maximizing the speed of the code is essential. For example, the task may be time critical, or it may be code that is used so often that optimizing it has a big payoff. This is actually the least plausible reason. With just-in-time (JIT) compilation, intensive computations coded in the Java programming language are not that much slower than compiled C code.
- In particular, the native code library you are calling must exist on the client machine, and it must work with the client machine architecture.
- In particular, the native code library you are calling must exist on the client machine, and it must work with the client machine architecture. To make calling native methods possible, Java technology comes with hooks for working with system libraries, and the JDK has a few tools to relieve some (but not all) of the programming tedium.
- Keep this in mind: if you use native methods, you lose portability.
- JNI = Java Native Interface
- JNI does not support any direct correspondence between Java platform classes and those in C++.
- The java programming language uses the keyword native for a native method, and you will obviously need to encapsulate the printf function in a class.
- Require a three-step process:
- Genreate a C stub for a function that translate between the Java call and the actual C function. The stub does this translation by taking parameter information off the virtual machine stack and passing it to the compiled C function.
- Create a special shared library and export the stub from it.
- Use a special method, called system.loadLibrary, to tell the Java runtime environment to load library from step 2.
static void android_media_MediaPlayer_start(JNIEnv *env, jobject thiz)
{
LOGV("start");
sp<MediaPlayer> mp = getMediaPlayer(env, thiz);
if (mp == NULL ) {
jniThrowException(env, "java/lang/IllegalStateException", NULL);
return;
}
process_media_player_call( env, thiz, mp->start(), NULL, NULL );
}
static JNINativeMethod gMethods[] = {
{"_start", "()V", (void *)android_media_MediaPlayer_start},
{"_stop", "()V", (void *)android_media_MediaPlayer_stop},
{"getVideoWidth", "()I", (void *)android_media_MediaPlayer_getVideoWidth},
{"getVideoHeight", "()I", (void *)android_media_MediaPlayer_getVideoHeight},
{"seekTo", "(I)V", (void *)android_media_MediaPlayer_seekTo},
{"_pause", "()V", (void *)android_media_MediaPlayer_pause},
{"isPlaying", "()Z", (void *)android_media_MediaPlayer_isPlaying},
};
static const char* const kClassPathName = "android/media/MediaPlayer";
// This function only registers the native methods
static int register_android_media_MediaPlayer(JNIEnv *env)
{
return AndroidRuntime::registerNativeMethods(env,"android/media/MediaPlayer", gMethods, NELEM(gMethods));
}
- The native keyword alerts the compiler that the method will be defined externally. Of course, native methods will contain no code in the Java programming language, and the method header is followed immediately by a terminating semicolon. This means, as you saw in the example above, native method declarations look similar to abstract method declarations.
- Native methods can be both static and non-static.
- You have a C or C++ program and would like to make a few calls to Java code, perhaps because the Java code is easier to program. Of course, you know how to call the Java methods. But you still need to add the Java virtual machine to your program so that the Java code can be interpreted. The so-called invocation API enables you to embed the Java virtual machine into a C or C++ program. Here is the minimal code that you need to initialize a virtual machine.
- Calling method created by Java:
- define parameter for JavaVM option, JavaVMInitArgs, jclass, jobjectArrary, jmethodID and so on;
- Create JavaVM by passing VM_arguments;
- Create class that has the API you want; 3. Call methods defined in class. 4. Destroy JavaVM.
- Calling method created by C or C++:
- Define a class with native method in Java;
- In Java class, using system.loadLibrary(“ClassName”) to load library implemented by C;
- Implemented C library by implementing native method defined in Java;
JNIEXPORT jobject JNICALL Java_Win32RegKey_getValue(JNIEnv* env,jobject this_obj,jobject name)
- In C code, calling method defined in Java:
- Get object class;
- Get the method ID;
- Call the method by passing object of class and method ID.
namespace android {
extern "C" status_t system_init()
{
LOGI("Entered system_init()");
sp<ProcessState> proc(ProcessState::self());
sp<IServiceManager> sm = defaultServiceManager();
LOGI("ServiceManager: %p\n", sm.get());
sp<GrimReaper> grim = new GrimReaper();
sm->asBinder()->linkToDeath(grim, grim.get(), 0); char propBuf[PROPERTY_VALUE_MAX];
property_get("system_init.startsurfaceflinger", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
// Start the SurfaceFlinger
SurfaceFlinger::instantiate();
}
property_get("system_init.startsensorservice", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
// Start the sensor service
SensorService::instantiate();
}
LOGI("System server: starting Android runtime.\n");
AndroidRuntime* runtime = AndroidRuntime::getRuntime();
LOGI("System server: starting Android services.\n");
JNIEnv* env = runtime->getJNIEnv();
if (env == NULL) { return UNKNOWN_ERROR;
}
jclass clazz = env->FindClass("com/android/server/SystemServer");
if (clazz == NULL) {
return UNKNOWN_ERROR;
}
jmethodID methodId = env->GetStaticMethodID(clazz, "init2", "()V");
if (methodId == NULL) {
return UNKNOWN_ERROR;
}
env->CallStaticVoidMethod(clazz, methodId); //C code call method of java
LOGI("System server: entering thread pool.\n");
ProcessState::self()->startThreadPool();
IPCThreadState::self()->joinThreadPool();
LOGI("System server: exiting thread pool.\n");
return NO_ERROR;
}
static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz) //native method by C
{
system_init();
}
/**
* JNI registration.
*/
static JNINativeMethod gMethods[] = { /** name, signature, funcPtr */
{ "init1", "([Ljava/lang/String;)V", (void*) android_server_SystemServer_init1 },
};
int register_android_server_SystemServer(JNIEnv* env)
{
return jniRegisterNativeMethods(env, "com/android/server/SystemServer",gMethods, NELEM(gMethods));
} };
Native Method的更多相关文章
- java.lang.IndexOutOfBoundsException at java.io.FileOutputStream.writeBytes(Native Method)
ss available : /usr/linkapp/data/linkapp/ddn_1440639847758_temp java.lang.IndexOutOfBoundsException ...
- Java Native Method
一.什么是java native method? "A native method is a Java method whose implementation is provided by ...
- NDK(3)java.lang.UnsatisfiedLinkError: Native method not found解决方法
调用native方法时报错如下 : “java.lang.UnsatisfiedLinkError: Native method not found.... ”: 原因分析: 链接器只看到了在so中 ...
- java.lang.UnsatisfiedLinkError: Native method not found 三种可能解决方案
so文件编译生成后,运行时,有时候会遇到java.lang.UnsatisfiedLinkError: Native method not found问题,有可能是以下三种因素: 一.Jni方法头部大 ...
- 修改Android 4.2.2的原生Camera引出的java.lang.UnsatisfiedLinkError: Native method not found,及解决方法
修改Android 4.2.2的原生Camera应用,做一些定制,将Camera的包名从之前的 package com.android.* 修改成了com.zhao3546.*. 调整后,应用可以正常 ...
- Mac OS X中报:java.io.UnixFileSystem.createFileExclusively(Native Method)的简单原因
这个博客太简单了!想到可能有其它朋友也遇到这个问题,就记录一下. 今天把一个之前在Windows上的Java项目放到Mac OS X上执行,本来认为应该非常easy的事情,结果还是报: Excepti ...
- eclipse启动tomcat正常,但是debug启动报错FATAL ERROR in native method:JDWP No transports initialized,jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197) ERROR: transport error 202: connect failed:Connection timed out
FATAL ERROR in native method:JDWP No transports initialized,jvmtiError=AGENT_ERROR_TRANSPORT_INIT(19 ...
- 待解决ava.lang.OutOfMemoryError: PermGen space at java.lang.ClassLoader.defineClass1(Native Method)
java.lang.OutOfMemoryError: PermGen space at java.lang.ClassLoader.defineClass1(Native Method) at ja ...
- at android.view.Surface.unlockCanvasAndPost(Native Method)
at android.view.Surface.unlockCanvasAndPost(Native Method) 在绘制动画特效的时候点击back键会报以上异常. 主要原因:当点击back按钮时A ...
- java.lang.Object.wait(Native Method)
java.lang.Object.wait(Native Method) java.lang.Object.wait(Object.java:502) java.util.TimerThread.ma ...
随机推荐
- 老男孩Day8作业:FTP
1.作业需求 开发简单的FTP: 1. 用户登陆 2. 上传/下载文件 3. 不同用户家目录不同 4. 查看当前目录下文件 5. 充分使用面向对象知识 2.流程图 3.目录结构 4.代码区 bin目录 ...
- [ZJOI2009]狼和羊的故事 BZOJ1412
题目描述 “狼爱上羊啊爱的疯狂,谁让他们真爱了一场:狼爱上羊啊并不荒唐,他们说有爱就有方向......” Orez听到这首歌,心想:狼和羊如此和谐,为什么不尝试羊狼合养呢?说干就干! Orez的羊狼圈 ...
- vue.js路由嵌套
<!DOCTYPE html> <html> <head> <title></title> <meta charset="u ...
- Kibana6.x.x——源码发布
从官方GitHub上克隆下来的源码自己如何发布? 我在Ubuntu系统中进行的开发,安装了yarn. 执行build命令为:$ yarn build 执行release命令为:$ yarn relea ...
- 本地访问Vmware虚机Web网站
情况:公司是域环境,Vmware网络设置的是NAT连接模式,里外装的都是Windows,虚机网络IP地址是自动获取的. 查看: 1.虚机Ping本地的IP地址可以Ping通: 2.本地Ping虚机的I ...
- How to Setup MySQL (Master-Slave) Replication in CentOS
The following tutorial aims to provide you a simple step-by-step guide for setting up MySQL (Master- ...
- 技巧:开启ubuntu系统的ssh服务
执行下述命令,安装 openssh 服务器. $ sudo apt-get install openssh-server 执行下面命令,启动 openssh $ sudo service ssh st ...
- 虚拟机 --- windows传输文件到虚拟机内
安装xftp 如果未安装的,可以点击上图红框的图标,会有链接....下载时记得选择school那一个身份,这是免费的...邮箱必须要写,因为下载链接会发送到你的邮箱里,如果没收到就换一个邮箱 下载完后 ...
- css连续的纯数字或字母强制换行
white-space:normal; word-break:break-all; white-space: normal|pre|nowrap|pre-wrap|pre-line|inherit;w ...
- tomcat异常[0]--java.lang.ClassNotFoundException: org.apache.taglibs.standard.tlv.JstlCoreTLV
自己建了一个项目,启动项目的时候,发生了java.lang.ClassNotFoundException: org.apache.taglibs.standard.tlv.JstlCoreTLV异常. ...