官术网_书友最值得收藏!

Introduction

Programming with Android NDK is essentially writing code in both Java and native languages such as C, C++, and assembly. Java code runs on Dalvik Virtual Machine (VM), while native code is compiled to binaries running directly on the operating system. Java Native Interface (JNI) acts like the bridge that brings both worlds together. This relationship between Java code, Dalvik VM, native code, and the Android system can be illustrated using the following diagram:

Introduction

The arrow in the diagram indicates which party initiates the interaction. Both Dalvik VM and Native Code run on top of Android system (Android is a Linux-based OS). They require the system to provide the execution environment. JNI is part of Dalvik VM, which allows Native Code to access fields and invoke methods at Java Code. JNI also allows Java Code to invoke native methods implemented in Native Code. Therefore, JNI facilitates the two-way communication between Native Code and Java Code.

If you are familiar with Java programming and C, or C++, or assembly programming, then learning programming with Android NDK is mostly learning JNI. JNI comes with both primitive and reference data types. These data types have their corresponding mapping data types in Java. Manipulating the primitive types can usually be done directly, since a data type is normally equivalent to a native C/C++ data type. However, reference data manipulation often requires the help of the predefined JNI functions.

In this chapter, we'll first cover various data types in JNI and demonstrate how to invoke native methods from Java. We then describe accessing the Java fields and calling Java methods from the native code. Finally, we will discuss how to cache data to achieve better performance, how to handle errors and exceptions, and how to use assembly in native method implementation.

Every recipe in this chapter comes with a sample Android project that illustrates the topic and related JNI functions. Because of the space constraint, we cannot list all the source code in the book. The code is a very important part of this chapter and it is strongly recommended that you download the source code and refer to it when going through the recipes.

Tip

JNI is a complex topic, and we tried to cover the most essential parts of it in the context of Android NDK programming. However, a single chapter is not enough to provide all the details. Readers may want to refer to Java JNI Specification at http://docs.oracle.com/javase/6/docs/technotes/guides/jni/ or the Java Native Interface: Programmer's Guide and Specification book at http://java.sun.com/docs/books/jni/. For Android-specific information, you can refer to JNI Tips at https://developer.android.com/guide/practices/jni.html.

主站蜘蛛池模板: 宾川县| 仁化县| 大英县| 电白县| 美姑县| 湘潭县| 新兴县| 滕州市| 新昌县| 满城县| 马公市| 陆良县| 郓城县| 博野县| 思茅市| 莒南县| 宿迁市| 马龙县| 繁峙县| 荆州市| 佛教| 海林市| 永清县| 南通市| 百色市| 香港| 曲松县| 阜平县| 汪清县| 连南| 周至县| 甘孜县| 镇远县| 收藏| 新河县| 武清区| 海伦市| 涿州市| 精河县| 绥德县| 图木舒克市|