My session in Wearable DevCon 2014, Burlingame, CA
[Note: now the conference is called "Wearable Tech Con" ]
The session gives an introduction to using the Java Native Interface (JNI) in Java, and in particular in the Android Platform. The session then covers the use of the Native Development Kit (NDK) for developing Android applications.
My session at AnDevCon, April 2014, Boston, MA
The session gives an introduction to using the Java Native Interface (JNI) in Java, and in particular in the Android Platform. The session then covers the use of the Native Development Kit (NDK) for developing Android applications.
@todo update description
Many students reach out to me asking for project ideas they can do as a summer project for learning. Here is an interesting project idea - implement your own java disassembler (and expand it to a VM later).
My session at AnDevCon, April 2014, Boston, MA
The session gives an introduction to using the Java Native Interface (JNI) in Java, and in particular in the Android Platform. The session then covers the use of the Native Development Kit (NDK) for developing Android applications.
@todo update description
Many students reach out to me asking for project ideas they can do as a summer project for learning. Here is an interesting project idea - implement your own java disassembler (and expand it to a VM later).
Core Java Developer Certification helps demonstrate an individual's overall comprehension and expertise of Java programming language. VSkills Core Java Developer Certification holders have more than a working familiarity with Java programs—they are technically skilled to take advantage of the breadth of features efficiently and effectively.
http://www.vskills.in/certification/Certified-Core-Java-Developer
So you've reversed you're first Android APK; now what? Java pseduocode is nice, but how do we modify the app? This is a crash course in reading and understanding Davlik opcodes. It will go through some basics then we will jump into a couple case studies to demonstrate some of the concepts. This talk should help testers who are interested in or do Android application assessments to better understand how to mess with the underlying code.
While coding in Java is (pretty) straight forward, some tasks require going beyond the borders of standard JVM coding practices in order to interface with low-level hardware & software programmatic APIs.
This slide will introduce the concept and basics of JNA, as well as discuss the probable caveats one might encounter when working with JNA, based on real production use-cases.
Mahika Tutorials sharing PPT slide for core java programming language. Go threw this slide and visit our YouTube page too
https://www.youtube.com/c/mahikatutorials
Using the Android Native Development Kit (NDK)DroidConTLV
Android NDK is used to integrate C/C++ code into Android applications. Learn when and how to use it ; and what it implies to do so from development, integration within Eclipse and Android Studio, to distribution.
Core Java Developer Certification helps demonstrate an individual's overall comprehension and expertise of Java programming language. VSkills Core Java Developer Certification holders have more than a working familiarity with Java programs—they are technically skilled to take advantage of the breadth of features efficiently and effectively.
http://www.vskills.in/certification/Certified-Core-Java-Developer
So you've reversed you're first Android APK; now what? Java pseduocode is nice, but how do we modify the app? This is a crash course in reading and understanding Davlik opcodes. It will go through some basics then we will jump into a couple case studies to demonstrate some of the concepts. This talk should help testers who are interested in or do Android application assessments to better understand how to mess with the underlying code.
While coding in Java is (pretty) straight forward, some tasks require going beyond the borders of standard JVM coding practices in order to interface with low-level hardware & software programmatic APIs.
This slide will introduce the concept and basics of JNA, as well as discuss the probable caveats one might encounter when working with JNA, based on real production use-cases.
Mahika Tutorials sharing PPT slide for core java programming language. Go threw this slide and visit our YouTube page too
https://www.youtube.com/c/mahikatutorials
Using the Android Native Development Kit (NDK)DroidConTLV
Android NDK is used to integrate C/C++ code into Android applications. Learn when and how to use it ; and what it implies to do so from development, integration within Eclipse and Android Studio, to distribution.
After reimplement many features several times in different platforms is time to think that it should be a better way. There are many frameworks that allows the developers to write the code once and deploy it "everywhere", but the final result is an app with a non native look and feel or with an emulated look and feel that the users can see and rate according to the quality.
There are other ways to develop apps for multiple platforms without rewriting the same code over and over. I'll talk about one of that ways which consists on developing the core with C++ and implement the UI natively. This method could sound very scary because of the C++ reputation (memory leaks, the standard library, etc), but with C++11 all this has been improved in a very sweet way, so maybe it is time to take an other look at this language and see how can we take advantage of it.
http://fr.droidcon.com/2014/agenda/
http://fr.droidcon.com/2014/agenda/detail?title=The+Android+Native+Development+Kit
The Android NDK is used to integrate C/C++ code into Android applications and libraries.
Learn how you can use the NDK and NDK-based libraries with Eclipse and Android Studio, and how you can debug and optimize your code.
Discover what changes from the new Android Runtime may break your integration, and how you can target new 64-bit architectures with the upcoming android L-release.
Speaker : Alexander Weggerle, Intel
Introduction to Java : Feature to Java, Java Virtual Machine, Differences between C++ and Java,
Part of Java, API Document, Starting a Java Program. Important Classes, Formatting the Output
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfJay Das
With the advent of artificial intelligence or AI tools, project management processes are undergoing a transformative shift. By using tools like ChatGPT, and Bard organizations can empower their leaders and managers to plan, execute, and monitor projects more effectively.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
1. NDK Primer
Ron Munitz
Founder & CEO - The PSCG
Founder & CTO - Nubo
ron@nubosoftware.com
ron@android-x86.org
https://github.com/ronubo/
Wearables
DevCon
March 2014
@ronubo
PSCG
3. About://Ron Munitz
● Distributed Fault Tolerant Avionic Systems
○ Linux, VxWorks, very esoteric libraries, 0’s and 1’s
● Highly distributed video routers
○ Linux
● Real Time, Embedded, Server bringups
○ Linux, Android , VxWorks, Windows, devices, BSPs, DSPs,...
● Distributed Android
○ Rdroid? Cloudroid? Too busy working to get over the legal naming, so
no name is officially claimed for my open source
● What currently keeps me busy:
○ Running the PSCG, a Embedded/Android consulting and Training
○ Managing R&D at Nubo
○ Lecturing at Afeka’s college of Engineering
○ Amazing present, endless opportunities. (Wish flying took less time)
@ronubo
PSCG
4. Agenda
● Part I: Java
○ Java Native Interface (JNI) - Theory
○ Hello World Tutorial - Practice
● Part II: JNI in the AOSP
● Part III: Native Android Apps
6. Introduction
The JNI is a native programming interface. It allows Java
code that runs inside a Java Virtual Machine (VM) to
interoperate with applications and libraries written in other
programming languages, such as C, C++, and assembly.
All JVM implementation need to implement the JNI
specification to allow compatibility with native code
libraries.
JNI to Java ⇔ __asm to C
7. Motivation
● The standard Java class library does not support the
platform-dependent features needed by the application.
○ For example NEON, SSSE3, ...
● You already have a library written in another language,
and wish to make it accessible to Java code through the
JNI.
● You want to implement a small portion of time-critical
code in a lower-level language such as assembly.
8. Wearable Motivation
● Reduce CPU cycles (and battery drain rate!) on
intensive computations
● Add designated features for simple add-on hardware
without having to support an entire ecosystem for that
● Media processing in Android: All is being done natively
this way or another
● Porting legacy code
● Protecting your logic and algorithms from rev-eng
9. JNI Pitfalls
● Subtle errors in the use of JNI can destabilize the entire JVM in
ways that are very difficult to reproduce and debug.
● An application that relies on JNI loses the platform portability Java
offers (a partial workaround is to write a separate implementation of
JNI code for each platform and have Java detect the operating
system and load the correct one at runtime).
● The JNI framework does not provide any automatic garbage
collection for non-JVM memory resources allocated by code
executing on the native side. Consequently, native side code (such
as assembly language) must assume the responsibility for explicitly
releasing any such memory resources that it itself acquires.
10.
11. JNI environment pointers
The JNI interface is organized like a C++ virtual function table. It
enables a VM to provide multiple versions of JNI function tables.
The JNI interface pointer is only valid in the current thread.
Native methods receive the JNI interface pointer as an argument.
The VM is guaranteed to pass the same interface pointer to a native
method when it makes multiple calls to the native method from the
same Java thread.
12. Loading and linking native methods
Native methods are loaded with the System.loadLibrary() method.
In the following example, the class initialization method loads a platform-
specific native library in which the native method f is defined:
class Cls {
native boolean f(int i, String s);
static {
System.loadLibrary(“pkg_Cls”);
}
}
The library pkg_Cls is platform specific. On a Unix derived system it will be
named libpkg_Cls.so and on windows system it will be named pkg_Cls.dll.
13. Loading and linking native methods
(cont.)
Dynamic linkers resolve entries based on their names. A native method
name is concatenated from the following components:
● the prefix Java_
● a mangled fully-qualified class name
● an underscore (“_”) separator
● a mangled method name
The signature of function f above is, as created by javah:
JNIEXPORT jboolean JNICALL Java_Cls_f(JNIEnv *, jobject, jint, jstring);
JNIEnv * - pointer to the JNI interface
jobject - a pointer to the calling java class for a static method or a
pointer to the calling java object for non-static method.
14. Referencing java objects
● Primitive types, such as integers, characters, and so on, are
copied between Java and native code (call by value)
● Arbitrary Java objects, on the other hand, are passed by
reference.
● The VM must keep track of all objects that have been passed to
the native code, so that these objects are not freed by the
garbage collector.
● The native code, in turn, must have a way to inform the VM that it
no longer needs the objects.
● The JNI divides object references used by the native code into two
categories: local and global references.
○ Local references are valid for the duration of a native method
call, and are automatically freed after the native method
returns.
○ Global references remain valid until they are explicitly freed.
15. Referencing java objects
(Cont.)
● Objects are passed to native methods as local references. All Java
objects returned by JNI functions are local references.
● The JNI allows the programmer to create global references from
local references. JNI functions that expect Java objects accept both
global and local references. A native method may return a local or
global reference to the VM as its result.
● Since the VM needs a certain amount of space to keep track of
a local reference, creating too many local references may
cause the system to run out of memory.
● Local references are only valid in the thread in which they are
created.
● Local references are automatically garbage collected once the
function returns.
16. Invocation API
Used to call java from c/c++ code.
The JNI interface pointer (JNIEnv) is valid only in the
current thread. Should another thread need to access the
Java VM, it must first call AttachCurrentThread() to attach
itself to the VM and obtain a JNI interface pointer. Once
attached to the VM, a native thread works just like an
ordinary Java thread running inside a native method. The
native thread remains attached to the VM until it calls
DetachCurrentThread() to detach itself.
17. Accessing fields and methods
● The JNI allows native code to access the fields and to call the
methods of Java objects.
● The JNI identifies methods and fields by their symbolic names and
type signatures.
● A two-step process factors out the cost of locating the field or
method from its name and signature. For example, to call the
method f in class cls, the native code first obtains a method ID, as
follows:
jmethodID methodId =
env->GetMethodID(cls, “f”, “(ILjava/lang/String;)D”);
The native code can then use the method ID repeatedly without the
cost of method lookup, as follows:
jdouble result = env->CallDoubleMethod(obj, methodID,
10, str);
18. Exception handling
There are two ways to handle an exception in native code:
● The native method can choose to return
immediately, causing the exception to be thrown in
the Java code that initiated the native method call.
● The native code can clear the exception by calling
ExceptionClear(), and then execute its own
exception-handling code.
After an exception has been raised, the native code must
first clear the exception before making other JNI calls.
19. JNI types and data structures
Java Type Native Type Description
boolean jboolean unsigned 8 bits
byte jbyte signed 8 bits
char jchar unsigned 16 bits
short jshort signed 16 bits
int jint signed 32 bits
long jlong signed 64 bits
float jfloat 32 bits
double jdouble 64 bits
21. JVM Type Signatures
Type Signature Java Type
Z boolean
B byte
C char
S short
I int
J long
F float
D double
L fully-qualified-class ; fully-qualified-class
[ type type[]
( arg-types ) ret-type method type
For example, the Java method:
long f(int n, String s, int[]
arr);
has the following type signature:
(ILjava/lang/String;[I)J
22. JNI types and data structures
Java Type Native Type Description
boolean jboolean unsigned 8 bits
byte jbyte signed 8 bits
char jchar unsigned 16 bits
short jshort signed 16 bits
int jint signed 32 bits
long jlong signed 64 bits
float jfloat 32 bits
double jdouble 64 bits
25. Step 1: HelloWorld.java
class HelloWorld
{
private native void print();
public static void main(String[] args)
{
new HelloWorld().print();
}
static {
System.loadLibrary("HelloWorld"); // Note: No “lib”, No “.so”.
}
}
Compile: javac HelloWorld.java .
Run: java HelloWorld
Fail: java.lang.UnsatisfiedLinkError: no HelloWorld in java.library.path . Not surprising…
26. Step 2: Auto Generate Headers
~/edu/jni$ javah HelloWorld # Note: javah takes a class name
:~/edu/jni$ cat HelloWorld.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloWorld */
#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/* Class: HelloWorld Method: print Signature: ()V */
JNIEXPORT void JNICALL Java_HelloWorld_print (JNIEnv *, jobject); // “Java” - because I didn’t use a package.
#ifdef __cplusplus
}
#endif
#endif
27. Step 3: HelloWorld.c
#include <stdio.h>
#include "HelloWorld.h"
JNIEXPORT void JNICALL Java_HelloWorld_print
(JNIEnv *env, jobject obj)
{
printf("Hello World!n");
}
Compile: gcc -shared -fPIC -I<YourJvmIncludePaths> HelloWorld.c -o libHelloWorld.so
Run: In a couple of slides.
Fail: Easily. GCC flags are subtle.
28. Step 3.5: Build the Shared Library
Let’s have a look at the following concrete
example:
gcc -shared -fPIC
-I/usr/lib/jvm/jdk1.7.0/include/linux -I/usr/lib/jvm/jdk1.7.0/include
HelloWorld.c -o libHelloWorld.so
-shared: Create a shared object. (In Windows: a “DLL”)
-fPIC: Position Independent Code - Always create Shared Object with that flag.
-I<et. al>: Location of jni.h, and files included from there.
-o libHelloWorld.so: Everything between “lib” and “.so” must match the name in loadLibrary().
29. Step 4: Run
java -Djava.library.path=. HelloWorld
Note: It is important to tell java where to look for your shared libraries.
Otherwise you will see the same error listed in Step 1.
Hello World!
31. The NDK in a nutshell
● Available as a JNI “SDK” to Android
application developers.
○ In the platform itself there is no need for it, just as
there is no need for the Android SDK
● Eases porting of existing Linux code to
Android
○ As long as it is not heavily depended on glibc
features, X, QT/GTK etc.
● Enables common code for multiple
architectures
○ On the nominal portable C/C++ code case
○ @see Application.mk
32. JNI in the Android platform
● @see
frameworks/base/services/java/com/android/server/SystemServer.java
● This is where the Java Android OS starts.
● And it is heavily relying on native functions
33. SystemServer.java revisited
public class SystemServer {
private static final String TAG = "SystemServer";
//...
private static native void nativeInit(); /*Called to initialize native system services.*/
public static void main(String[] args) {
// ...
// Set runtime libary property (Dalvik/ART/..) ...
// Set initial system time (to workaround some negative value bugs) ...
// Enable profiler snapshot if profiler is enabled ...
// Take care of HeapSize for the System Server which never dies ...
// ...
System.loadLibrary("android_servers");
Slog.i(TAG, "Entered the Android system server!");
nativeInit(); /* Initializes native services - This is a JNI call to
frameworks/base/services/jni/com_android_server_SystemServer.cpp …
See next slide*/
ServerThread thr = new ServerThread();
thr.initAndLoop(); // Note to self: so long init2()!!!
}
}
34. com_android_server_SystemServer.cpp
● Path: frameworks/base/services/jni/
● namespace: Android
● C, C++, java, JNI:
○ com/android/server/SystemServer.java
○ com_android_server_SystemServer.cpp
○ Note: Name convention should suffice.
However, when adding to the SystemServer, it is advised to also
jniRegisterNativeMethods (@see libnativehelper/…)
● As per the code itself…
static void android_server_SystemServer_nativeInit(JNIEnv* env, jobject clazz) {
char propBuf[PROPERTY_VALUE_MAX];
property_get("system_init.startsensorservice", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
SensorService::instantiate(); // Start the sensor service which is pure native
} // @see frameworks/native/services/sensorservice
}
35. onload.cpp
● jint JNI_OnLoad(JavaVM* vm, void* reserved)
Called by default by the JVM upon System.loadLibrary()
● Loads the JNI Environment (uses JNI_VERSION_1_4)
● Registers native servers by calling
register_android_server_<Name>(env);
<Name> can be one of:
PowerManagerService SerialService
InputApplicationHandle InputWindowHandle
InputManager LightsService
AlarmManagerService UsbDeviceManager
UsbHostManager VibratorService
SystemServer location_GpsLocationProvider
location_FlpHardwareProvider connectivity_Vpn
AssetAtlasService ConsumerIrService
36. register_android_server_<Name>
and jniRegisterNativeMethods
● As we saw, libandroid_servers’s JNI_OnLoad() registers
each of the JNI servers.
● Each explicitly registers the exported JNI constructs,
by providing their signatures to libnativehelper’s
jniRegisterNativeMethods() method
● Which in turns calls JNI’s RegisterNatives() method.
● This is also essential because the AOSP uses naming
conventions that do not start with the “Java_” prefix, and
therefore cannot be invoked unless explicitly
registered by RegisterNatives()
37. JNI_onLoad()
● The context of the VM is available only in the
called thread.
● Which means that calling back Java is
possible only if:
○ It is a call back from a thread invoked by Java
○ Somewhere a reference is stored globally for all/for
relevant threads
● Do JVM caching on onLoad()
● Free on onUnload()
39. Native project directory structure
● Source Control:
○ ./ - Root. Home of manifest, ant/gradle, ...
○ src - Java source files
○ lib - Libaries. Including generated libraries and .so’s
○ res - Resources
○ assets - Assets (raw resources etc.)
○ jni - Native code. Home of *.c*, *.h*, *.mk
■ Android.mk - Makefile
■ Application.mk - Application definition (APP_*)
● Generated
○ gen - generated java files
○ obj - Native object files
○ bin - Binaries
40. NDK App development with Android
1. Java code - as in Java’s JNI.
2. Native code - as in Java’s JNI
3. javah - provide class path (bin/…)
4. Makefiles
a. Android.mk - Android makefile.
i. e.g. include $(BUILD_SHARED_LIBRARY)
b. Application.mk - Application definitions
i. e.g. APP_ABI := all -
5. ndk-build - builds native code
6. ant/gradle - builds APK and bundles .so’s in
lib
42. jni/
Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := hello-jni.c
include $(BUILD_SHARED_LIBRARY)
Application.mk
APP_ABI := x86 armeabi
obj/local/x86/libhello-jni.so
obj/local/armeabi/libhello-jni.so
ndk-build
43. src/
com/example/hellojni/HelloJni.java
package com.example.hellojni;
import android.app.Activity;
import android.widget.TextView;
import android.os.Bundle;
public class HelloJni extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText( stringFromJNI() );
setContentView(tv);
}
public native String stringFromJNI();
public native String unimplementedStringFromJNI(); // Catch: Call --> exception
static {
System.loadLibrary("hello-jni");
}
}
44. The Native App Glue
● Enables writing fully native applications
○ That is 0 java files
● Usually good for porting games
● Or porting other heavy event machine logic
● Requires implementation of your own Looper
● Requires a manifest declaration:
<activity android:name="android.app.NativeActivity"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<!-- Tell NativeActivity the name of or .so -->
<meta-data android:name="android.app.lib_name"
android:value="native-activity" />
...
45. Publishing Applications
● Two approaches each has its pros and cons
● The first: Compile with all the libraries you
can (APP_ABI := all)
○ Easier to maintain.
○ At the cost of larger (and sometimes huge) APK’s
● The second: Create version per architecture
○ Create application with a slightly modifed version
code at the MSB.
○ This is the PlayStore way of identifying multiple
APKs for the same version