Android JNI Call

Source: Internet
Author: User

android JNI is a link between the Android Java and C + + parts, and the full use of JNI requires Java code and C/S code. where C + + code is used to generate library files, Java code is used to refer to C + + library files and to call C + + methods.

Android Java part code:

/*
* Copyright (C) The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You are not a use this file except in compliance with the License.
* Obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable or agreed to writing, software
* Distributed under the License is distributed on a "as is" BASIS,
* Without warranties or CONDITIONS of any KIND, either express or implied.
* See the License for the specific language governing permissions and
* Limitations under the License.
*/

Package com.example.android.simplejni;

Import android.app.Activity;
Import Android.os.Bundle;
Import Android.widget.TextView;

public class Simplejni extends Activity {
/** called when the activity is first created. */
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
TextView TV = new TextView (this);
int sum = Native.add (2, 3);
int minus = Native.minus (10, 3);
Tv.settext ("10-3 =" + integer.tostring (minus));
Setcontentview (TV);
}
}

Class Native {
static {
The runtime would add "Lib" on the front and ". O" on the end of
The name supplied to LoadLibrary.
System.loadlibrary ("Simplejni");
}

static native int add (int a, int b);
static native int minus (int a, int b);
}

Java code Description:1)Simplejni is an activity class object that generates a class object that invokes the JNI function in the class object, calls the Jni method, and finally displays the result of the Jni method on the title bar;2)Simplejni is a class that references and declares JNI libraries and functions, where system.loadlibrary () functions are used to refer to the JNI library, and the default JNI libraries are placed in the/system/lib/directory of the Android system; static native int add (int a, int b); To declare a function in a JNI library that needs to be used in a Java program;The code for the Java part of JNI ends here, and it concludes that there are two things to do in Java code:1) Use the System.loadlibrary () function to refer to the JNI library;2) Declare a function that invokes the JNI library and add the native keyword before it;


Android/C + + section code:

/*
* Copyright (C) The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You are not a use this file except in compliance with the License.
* Obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable or agreed to writing, software
* Distributed under the License is distributed on a "as is" BASIS,
* Without warranties or CONDITIONS of any KIND, either express or implied.
* See the License for the specific language governing permissions and
* Limitations under the License.
*/

#define LOG_TAG "Simplejni native.cpp"
#include <utils/Log.h>

#include <stdio.h>

#include "jni.h"

Static Jint
Add (jnienv *env, Jobject thiz, jint A, Jint b) {
int result = a + B;
Alogi ("%d +%d =%d", a, b, result);
return result;
}

Static Jint
Minus (JNIEnv *env, Jobject thiz, jint A, Jint b) {
int result = A-B;
Alogi ("%d-%d =%d", a, b, result);
return result;
}


static const char *classpathname = "com/example/android/simplejni/native";

Static Jninativemethod methods[] = {
{"Add", "(II) I", (void*) add},
{"Minus", "(II) I", (void*) minus}
};

/*
* Register Several native methods for one class.
*/
static int Registernativemethods (jnienv* env, const char* ClassName,
jninativemethod* gmethods, int nummethods)
{
Jclass Clazz;

Clazz = Env->findclass (className);
if (clazz = = NULL) {
Aloge ("Native Registration unable to find class '%s '", className);
return jni_false;
}
if (Env->registernatives (Clazz, Gmethods, Nummethods) < 0) {
Aloge ("Registernatives failed for '%s '", className);
return jni_false;
}

return jni_true;
}

/*
* Register native methods for all classes we know about.
*
* Returns jni_true on success.
*/
static int registernatives (jnienv* env)
{
if (!registernativemethods (env, Classpathname,
Methods, sizeof (methods)/sizeof (Methods[0]))) {
return jni_false;
}

return jni_true;
}


// ----------------------------------------------------------------------------

/*
* This was called by the VM when the shared library is first loaded.
*/

typedef Union {
jnienv* env;
void* venv;
} unionjnienvtovoid;

Jint jni_onload (javavm* vm, void* reserved)
{
Unionjnienvtovoid uenv;
Uenv.venv = NULL;
Jint result =-1;
jnienv* env = NULL;

Alogi ("Jni_onload");

if (Vm->getenv (&uenv.venv, jni_version_1_4)! = JNI_OK) {
Aloge ("Error:getenv failed");
Goto bail;
}
env = uenv.env;

if (registernatives (env) = Jni_true) {
Aloge ("Error:registernatives failed");
Goto bail;
}

result = Jni_version_1_4;

Bail:
return result;
}

JNI C + + code description:1) jni_onload () function. This function is called to execute when the Java program calls System.loadlibrary (), to register the JNI function with JAVAVM, and so on. In this example, we first get the thread of the current application with the parameter JAVAVM (Java Virtual machine pointer), which is: jnienv. The function pointers implemented by the native are then registered by calling Android::androidruntime::registernativemethods (). 2) The mapping between the JNI function and the Java calling function. Use Jninativemethod to associate the name of the function called by Java with the function name of the JNI implementation;3) The implementation of the JNI function;ANDROID.MK Code:
#
# Copyright (C) The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# You are not a use of this file except in compliance with the License.
# Obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# unless required by applicable or agreed to writing, software
# Distributed under the License is distributed on a "as is" BASIS,
# without warranties or CONDITIONS of any KIND, either express or implied.
# See the License for the specific language governing permissions and
# Limitations under the License.
#

# This makefile shows how to build a shared library and an activity that
# Bundles the shared library and calls it using JNI.

Top_local_path:= $ (call My-dir)

# Build Activity

Local_path:= $ (Top_local_path)
Include $ (clear_vars)

Local_module_tags: = Samples

Local_src_files: = $ (call all-subdir-java-files)

Local_package_name: = Simplejni

Local_jni_shared_libraries: = Libsimplejni

local_proguard_enabled: = disabled

Local_sdk_version: = Current

Include $ (build_package)

# ============================================================

# Also Build all of the sub-targets under this one:the shared library.
Include $ (call all-makefiles-under,$ (Local_path))

It is important to note that:1) The Code of the JNI C + + section needs to be compiled on the Android source tree, and after the compilation is done, my practice is to upload the generated. So via the ADB push method to the/system/lib/directory of the Android virtual machine;2) Java code can be compiled directly under Eclipse and executed on the virtual machine;
Compile the JNI C + + section code (at the root of the Android kernel source code):#make XXXXthen generate the xxx.so in the out/target/product/generic/system/lib/directory
students who need source code: http://download.csdn.net/detail/tianyeming/9000955


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android JNI Call

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.