1. 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.
  2. There are three obvious reasons why that may be the right choice:
    1. 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.
    2. Your application requires access to system features or devices, and using Java technology would be cumbersome at best, or impossible at worst.
    3. 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.
  3. In particular, the native code library you are calling must exist on the client machine, and it must work with the client machine architecture.
  4. 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.
  5. Keep this in mind: if you use native methods, you lose portability.
  6. JNI = Java Native Interface
  7. JNI does not support any direct correspondence between Java platform classes and those in C++.
  8. 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.
  9. Require a three-step process:
    1. 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.
    2. Create a special shared library and export the stub from it.
    3. Use a special method, called system.loadLibrary, to tell the Java runtime environment to load library from step 2.
    4.  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));
      }
  10. 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.
  11. Native methods can be both static and non-static.
  12. 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.
  13. Calling method created by Java:
    1. define parameter for JavaVM option, JavaVMInitArgs, jclass, jobjectArrary, jmethodID and so on;
    2. Create JavaVM by passing VM_arguments;
    3. Create class that has the API you want;  3. Call methods defined in class. 4. Destroy JavaVM.
  14. Calling method created by C or C++:
    1. Define a class with native method in Java;
    2. In Java class, using system.loadLibrary(“ClassName”) to load library implemented by C;
    3. Implemented C library by implementing native method defined in Java;
 JNIEXPORT jobject JNICALL Java_Win32RegKey_getValue(JNIEnv* env,jobject this_obj,jobject name)
  1. In C code, calling method defined in Java:
    1. Get object class;
    2. Get the method ID;
    3. Call the method by passing object of class and method ID.
  2.  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的更多相关文章

  1. java.lang.IndexOutOfBoundsException at java.io.FileOutputStream.writeBytes(Native Method)

    ss available : /usr/linkapp/data/linkapp/ddn_1440639847758_temp java.lang.IndexOutOfBoundsException ...

  2. Java Native Method

    一.什么是java native method? "A native method is a Java method whose implementation is provided by ...

  3. NDK(3)java.lang.UnsatisfiedLinkError: Native method not found解决方法

    调用native方法时报错如下 : “java.lang.UnsatisfiedLinkError: Native method not found....  ”: 原因分析: 链接器只看到了在so中 ...

  4. java.lang.UnsatisfiedLinkError: Native method not found 三种可能解决方案

    so文件编译生成后,运行时,有时候会遇到java.lang.UnsatisfiedLinkError: Native method not found问题,有可能是以下三种因素: 一.Jni方法头部大 ...

  5. 修改Android 4.2.2的原生Camera引出的java.lang.UnsatisfiedLinkError: Native method not found,及解决方法

    修改Android 4.2.2的原生Camera应用,做一些定制,将Camera的包名从之前的 package com.android.* 修改成了com.zhao3546.*. 调整后,应用可以正常 ...

  6. Mac OS X中报:java.io.UnixFileSystem.createFileExclusively(Native Method)的简单原因

    这个博客太简单了!想到可能有其它朋友也遇到这个问题,就记录一下. 今天把一个之前在Windows上的Java项目放到Mac OS X上执行,本来认为应该非常easy的事情,结果还是报: Excepti ...

  7. 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 ...

  8. 待解决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 ...

  9. at android.view.Surface.unlockCanvasAndPost(Native Method)

    at android.view.Surface.unlockCanvasAndPost(Native Method) 在绘制动画特效的时候点击back键会报以上异常. 主要原因:当点击back按钮时A ...

  10. java.lang.Object.wait(Native Method)

    java.lang.Object.wait(Native Method) java.lang.Object.wait(Object.java:502) java.util.TimerThread.ma ...

随机推荐

  1. 再谈hive-1.0.0与hive-1.2.1到JDBC编程忽略细节问题

    不多说,直接上干货,这个问题一直迷惑已久,今天得到亲身醒悟. 所以,建议hadoop-2.6.0.tar.gz的用户与hive-1.0.0搭配使用.当然,也可以去用高版本去覆盖它. log4j:WAR ...

  2. 记录下自己安装cuda以及cudnn

    之前已经装过一次了,不过没有做记录,现在又要翻一堆博客安装,长点记性,自己记录下. 环境 ubuntu16.04 python2.7 商家送过来时候已经装好了显卡驱动,所以省去了一大麻烦. 剩下的就是 ...

  3. 项目笔记《DeepLung:Deep 3D Dual Path Nets for Automated Pulmonary Nodule Detection and Classification》(三)(上)结果评估

    在(一)中,我将肺结节检测项目总结为三阶段,这里我要讲讲这个项目的第三阶段,至于第二阶段,由于数据增强部分的代码我始终看不大懂,先不讲. 结果评估的程序在evaluationScript文件夹下,这个 ...

  4. apache 压缩 gzip

    配置 编辑httpd.conf文件 去掉 #LoadModule headers_module modules/mod_headers.so 前面的注释# 去掉 #LoadModule deflate ...

  5. Github如何在Linux系统下创建本地仓库

    一.电脑上安装 Git Ubuntu安装GIt:  apt-get install git 查看版本信息:    git version 配置Git用户信息  输入: git config --glo ...

  6. Codeforces Round #316 (Div. 2) A

    Description The country of Byalechinsk is running elections involving n candidates. The country cons ...

  7. day23 模块

    1. 模块 1. 首先,我们先看个老生常谈的问题. 什么是模块. 模块就是一个包含了python定义和声 明的文件, 文件名就是模块的名字加上.py后缀. 换句话说我们目前写的所有的py文件都可以 看 ...

  8. Jenkins自动化CI CD流水线之4--Master-Slave架构

    一.介绍 jenkins的Master-slave分布式架构主要是为了解决jenkins单点构建任务多.负载较高.性能不足的场景. Master/Slave相当于Server和agent的概念.Mas ...

  9. element-ui表单验证(电话,邮箱)

    element-ui Form表单验证 最近刚好使用了element-ui的form表单,官网只提供的示例,这里把一些常用的验证记录下来,方便后期查找最终的效果是这样的, 这个表单里还加入了一下其他组 ...

  10. $.extend({},defaults, options)

    1.$.extend({},defaults, options) 这样做的目的是为了保护包默认参数.也就是defaults里面的参数. 做法是将一个新的空对象({})做为$.extend的第一个参数, ...