[Android Beginner] NDK Introductory Experience method call

Source: Internet
Author: User

This article belongs to self-review, content repetition do not be offended

How do I call Java code in the custom bottom C of Android apps? This is the plan of self-revision.

First, I have to create a demo with the following structure:


1. Create an interface class Nativedataprovider, whose role is to call the C method and then callback the Java method

public class Nativedataprovider {static final String TAG = "Nativedataprovider";p rivate Context context;public nativedata Provider (Context context) {This.context = context;} Call C in code public native void Callccode ();p ublic native int callcadd (int i,int j);p ublic native void Callcprintstring ();//In C in Call Java Org.jan.ndk.example.NativeDataProvider method hellofrmjavapublic void Hellofromjava () {log.i (TAG, "Hello from Java! "); Toast.maketext (context, "Hello from Java", Toast.length_short). Show (); The method that calls the parameter string in C is public void printstring (String str) {LOG.I (TAG, "[from Java]:" +STR); Toast.maketext (Context, "PRINTSTRING->STR:" +str, Toast.length_short). Show (); method of calling int parameter in c public int Add (int i,int j) {int result = I+J; LOG.I (TAG, "result is" +result); Toast.maketext (Context, "add->result=" +result, Toast.length_short). Show (); return result;}}

2. Create Android.mk

Local_path: = $ (call My-dir) include $ (clear_vars) local_module    : = jni_demolocal_src_files: = jni_demo.c# Add Log library Local_ldlibs + =-llog include $ (build_shared_library)
3. Create JNI, the C code, before creating the Nativedataprovider header file, to the project directory/bin/classes, callingJavah Org.jan.ndk.example.NativeDataProvider

It will generate Org_jan_ndk_example_nativedataprovider.h

/* Don't EDIT this file-it are machine generated */#include <jni.h>/* Header for class org_jan_ndk_example_natived Ataprovider */#ifndef _included_org_jan_ndk_example_nativedataprovider#define _included_org_jan_ndk_example_    Nativedataprovider#ifdef __cplusplusextern "C" {#endif */* * Class:org_jan_ndk_example_nativedataprovider * Method: Callccode * Signature: () V */jniexport void Jnicall java_org_jan_ndk_example_nativedataprovider_callccode (JNIENV *, Job ject);/* * Class:org_jan_ndk_example_nativedataprovider * Method:callcadd * Signature: (II) I */jniexport jint JNI Call Java_org_jan_ndk_example_nativedataprovider_callcadd (JNIEnv *, Jobject, Jint, jint); */* Class:org_jan_ndk_exa Mple_nativedataprovider * method:callcprintstring * Signature: () V */jniexport void Jnicall Java_org_jan_ndk_example_n Ativedataprovider_callcprintstring (jnienv *, jobject); #ifdef __cplusplus} #endif #endif

where you see signature: () V This is similar to the method signature.

For example:

har* classname = "Org/jan/ndk/example/nativedataprovider";
Jclass Dpclazz = (*env)->findclass (env, classname);

This is obtained by jnienv pointer to the class object.


Jmethodid Methodid = (*env)->getmethodid (env, Dpclazz, "Hellofromjava", "() V") ;

Getmethodid refers to getting a defined method from Java, the second parameter is a class object, the third parameter is the method name, and the fourth is the method signature (you can see signature from the file)

See method Signature Method: Enter the project \bin\classes, command: Javap-s org.jan.ndk.example.NativeDataProvider

The approximate meaning of "() v" is that there is no parameter in the parentheses, that is, there is no entry, and V is void with no return value.



Here is the C main code (see note for details):

#include "org_jan_ndk_example_nativedataprovider.h" #include <string.h> #include <android/log.h> #define Log_tag "System.out" #define LOGD (...) __android_log_print (Android_log_debug, Log_tag, __va_args__) #define LOGI (...) _ _android_log_print (Android_log_info, Log_tag, __va_args__) jniexport void Jnicall Java_org_jan_ndk_example_ Nativedataprovider_callccode (JNIENV * env, Jobject obj) {//calls the Hellofromjava () method in the Nativedataprovider object//Gets to an object, Gets the method in the object, calls the obtained method Logi ("in Code"),//nativedataprovider the full class name org.jan.ndk.example.nativedataproviderchar* classname = " Org/jan/ndk/example/nativedataprovider "; Jclass Dpclazz = (*env)->findclass (env, classname); if (Dpclazz = = 0) LOGI (" Org.jan.ndk.example.NativeDataProvider.class not find!!! "); Elselogi ("Org.jan.ndk.example.NativeDataProvider.class find!!!"); /using the Getmethodid method provided in Jni.h, get jmethodid, incoming parameters ①jnienv pointer ②class Object ③ method name ④ method signature, where method name and method signature determine a method, the method signature is the method's return value and parameters of the unique indicator;// Parameter description: The second parameter is the class object, the third parameter is the method name, the fourth parameter is the signature of the method, gets the call to the Methodjmethodid methOdid = (*env)->getmethodid (env, Dpclazz, "Hellofromjava", "() V"), if (Methodid = = 0) Logi ("Method Hellofromjava not find" !!!"); Elselogi ("Method Hellofromjava find!!!"); * * Call method Void (*callvoidmethod) (jnienv*, Jobject, Jmethodid, ...); * Parameter Description: The following ... is a mutable parameter, if the method with the return value void has parameters, the parameters are arranged in order */logi ("before Call method");(*env)->callvoidmethod (env, obj, methodid); Logi ("After Call method"); Jniexport void Jnicall java_org_jan_ndk_example_nativedataprovider_callcprintstring (JNIEnv *env, Jobject obj) {// Call the Hellofromjava () method in the Dataprovider object//Get to an object, get the method in the object, call the obtained method Logi ("in Code"),//nativedataprovider the full class name org.jan.ndk.example.nativedataproviderchar* classname = "Org/jan/ndk/example/nativedataprovider"; Jclass dpclazz = (* ENV)->findclass (env, classname); if (Dpclazz = = 0) logi ("Class not find!!!"); Elselogi ("Class find!!!"); /Parameter Description: The second parameter is the class object, the third parameter is the method name, the fourth parameter is the signature of the method, gets the call to the Methodjmethodid Methodid = (*env)->getmethodid (env, Dpclazz, " Printstring "," (ljava/lang/string;) V "); if (Methodid = = 0) Logi ("Method not find!!!"); Elselogi ("Method Find!!!"); * * Call method Void (*callvoidmethod) (jnienv*, Jobject, Jmethodid, ...); * Parameter Description: The following ... is a mutable parameter, if the method with the return value void has parameters, the parameters are sorted in order */logi ("before Call method");(*env)->callvoidmethod (env, obj, Methodid, (*env)- >newstringutf (env, "Printstring method Callback success!!")); Logi ("After Call method"); /* * Actual development situation * C Code engineer give us first.h first.c, we only need to introduce first.h, then we can use the method of */jniexport Jint Jnicall Java_org_jan_ndk_exampl E_nativedataprovider_callcadd (jnienv *env, Jobject obj, jint A, Jint b) {//Call Dataprovider () method in Hellofromjava object// Gets to an object, gets the method in the object, invokes the obtained method Logi ("in Code test_add=>");//nativedataprovider Full class name org.jan.ndk.example.nativedataproviderchar* classname = "Org/jan/ndk/example/nativedataprovider"; Jclass dpclazz = (* ENV)->findclass (env, classname); if (Dpclazz = = 0) logi ("Class not find!!!"); Elselogi ("Class find!!!"); /Parameter Description: The second parameter is a class object, the third parameter is the method name, the fourth parameter is the signature of the method, gets the call to Methodjmethodid Methodid = (*env)->getmethodid (env,Dpclazz, "Add", "(II) I"), if (Methodid = = 0) Logi ("Method not find!!!"); Elselogi ("Method Find!!!"); * * Call method Void (*callvoidmethod) (jnienv*, Jobject, Jmethodid, ...); * Parameter Description: The following ... is a mutable parameter, if the method with the return value void has parameters, the parameters are sorted in order */return (*ENV)->callintmethod (env, obj, Methodid, A, b);}

4. Compile jni and manually execute Ndk-build in the demo directory

5.android of code:

public class Mainactivity extends Actionbaractivity {private static final String TAG = "mainactivity";p rivate static Nativ Edataprovider ndp;static{system.loadlibrary ("Jni_demo");} @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); NDP = new Nativedataprovider (this); if (savedinstancestate = = null) {Getsupportfragmentmanager (). BeginTransaction (). Add (R.id.container, New Placeholderfragment ()). commit ();}} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} @Overridepublic boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here. The action bar will//automatically handle clicks on the Home/up button so long//as you specify a parent activity in and RoidManifest.xml.int id = item.getitemid (); if (id = = r.id.action_settings) {return true;} Return Super.onoptionsitemselected (item);} /** * A placeholder fragment containing a simple view. */public Static class Placeholderfragment extends Fragment implements Onclicklistener {private Button Callvoidmethod, Cal Lstringmethod, Callintmethod;public placeholderfragment () {} @Overridepublic View Oncreateview (layoutinflater Inflater, ViewGroup container,bundle savedinstancestate) {View Rootview = inflater.inflate (R.layout.fragment_main, Container,false); Callvoidmethod = (Button) Rootview.findviewbyid (r.id.call_void_method_btn); CallStringMethod = ( button) Rootview.findviewbyid (r.id.call_string_parameter_method), Callintmethod = (button) Rootview.findviewbyid ( R.id.call_int_parameter_method); Callvoidmethod.setonclicklistener (this); Callstringmethod.setonclicklistener ( This), Callintmethod.setonclicklistener (this); return Rootview;} @Overridepublic void OnClick (View v) {switch (V.getid ()) {case R.id.call_void_method_btn:ndp.callccode (); break;case R.id.call_string_parameter_method:ndp.callcprintstring (); break;Case R.id.call_int_parameter_method:ndp.callcadd (2,3); 

The implementation results are as follows:



Code sample Download: Please open Ruyi door download




[Android Beginner] NDK Introductory Experience method 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.