JNI Learning 2:android calls the C language method and calls the Android method with C language

Source: Internet
Author: User

#include <jni.h> #include <stdio.h> #include <stdlib.h> #include <jni.h> #include <android/ log.h> #define LOG_TAG "System.out"//log garbled when you set the project file encoding to Utf-8/**debug level log: Android_log_debug: level, Log_tag: tags, __va_ ARGS__: Log content) **/#define LOGD (...) __android_log_print (android_log_debug,log_tag,__va_args__)/**info level log: ANDROID_ Log_info: Level, Log_tag: tags, __va_args__: log content) **/#define Logi (...) __android_log_print (Android_log_info,log_tag,__va_ args__) extern "C" {/***java language string to C language char***/char* Jstringtochar (jnienv *env, jstring jstr) {char* RTN = Null;jclass cl asstring = Env->findclass ("java/lang/string"); jstring Strencode = Env->newstringutf ("GB2312"); JmethodID mid = Env->getmethodid (classtring, "GetBytes", "(ljava/lang/string;) [B"); Jbytearray Barr = (Jbytearray) env-> Callobjectmethod (Jstr, Mid, Strencode); Jsize alen = Env->getarraylength (Barr); jbyte* ba = env-> Getbytearrayelements (Barr, Jni_false); if (Alen > 0) {rtn = (char*) malloc (alen + 1); memcpy (RTN, BA, Alen); Rtn[alen] = 0;} Env->releasebytearrayelements (Barr, BA, 0); return RTN;} Jniexport jstring Java_com_example_ndktest_jniprovideer_hello (jnienv *env,jobject obj) {LOGD ("%s", "haha"); return Env->newstringutf ("Hello from JNI!");} /***2 integer Add ***/jniexport jint java_com_example_ndktest_jniprovideer_add (jnienv *env,jobject obj,jint x,jint y) {return X+y;} /*** string Conversion ***/jniexport jstring Java_com_example_ndktest_jniprovideer_sayhello (jnienv *env,jobject obj,jstring jstr) {char* P=jstringtochar (ENV,JSTR); Logi ("sss%s", p);//strcat (p,helloword) means Helloword? Stitching to P back Env->newstringutf (strcat (P, "Helloword"));} /*** an array of integers with each element plus 10***/jniexport Jintarray java_com_example_ndktest_jniprovideer_getintarray (JNIEnv *env,jobject obj, Jintarray Jintarr) {//Get array length int len=env->getarraylength (JINTARR);  Logi ("len=%d", Len);//get integer array address jint* arr=env->getintarrayelements (jintarr,0); for (int i=0; i < Len; i++) {* (arr+i) +=10;} return Jintarr;} /*** calls the Java object in the active method String getString () * () ljava/lang/string; indicates that the parameter is empty and the return value is sTring***/jniexport void java_com_example_ndktest_jniprovideer_getjavamethodforgetstring (JNIEnv *env,jobject obj) { Jclass Classz=env->findclass ("Com/example/ndktest/jniprovideer"), if (classz==0) {Logi ("Can ' t find Class");} Else{logi ("Find Class");} Jmethodid Javamethod=env->getmethodid (CLASSZ, "getString", "() ljava/lang/string;"); if (javamethod==0) {Logi ("can ' t find Menthod");}    Else{logi ("Find Menthod");} Jstring result= (jstring) Env->callobjectmethod (Obj,javamethod); char* P=jstringtochar (Env,result); Logi ("result=%s", p);} /*** the active call to the Java object in the method int getadd (int x,int y) * (II) I means the parameter is 2 integers, the return value is an integer ***/jniexport void java_com_example_ndktest_ Jniprovideer_getjavamethodforgetadd (jnienv *env,jobject obj) {jclass Classz=env->findclass ("Com/example/ndktest /jniprovideer "), if (classz==0) {Logi (" Can ' t find Class ");} Else{logi ("Find Class");} Jmethodid Javamethod=env->getmethodid (CLASSZ, "Getadd", "(II) I"), if (javamethod==0) {Logi ("can ' t find Menthod");} Else{logi ("Find Menthod");} int result= Env->callintmeThod (obj,javamethod,7,7); Logi ("result=%d", result);} /*** active call in Java object method void Getvoidmethod (String x) * (ljava/lang/string;) v for argument is String, return value is null ***/jniexport void Java_com_ Example_ndktest_jniprovideer_getjavamethodforgetvoidmethod (jnienv *env,jobject obj) {jclass classz=env-> Findclass ("Com/example/ndktest/jniprovideer"), if (classz==0) {Logi ("Can ' t find Class");} Else{logi ("Find Class");} Jmethodid Javamethod=env->getmethodid (CLASSZ, "Getvoidmethod", "(ljava/lang/string;) V"); if (javaMethod==0) {LOGI ("Can ' t find Menthod");} Else{logi ("Find Method");} Env->callvoidmethod (Obj,javamethod,env->newstringutf ("abc"));}}

  

Package Com.example.ndktest;import Android.util.log;public class Jniprovideer {  static{  system.loadlibrary ( "Ndktest");  }  public native int Add (int x,int y);  Public native string SayHello (string s);  Public native int[] Getintarray (int[] ints);  Public native String hello ();  public native void Getjavamethodforgetstring ();  public native void Getjavamethodforgetadd ();  public native void Getjavamethodforgetvoidmethod ();  /**   * method to make the C language active call * @return */public String getString () {  return "Hello";  } /** * method to make the C language active call * @return *  /public int getadd (int x,int y) {  return x+y;  }  /**   * method to make the C language active call * @return */public    void Getvoidmethod (String x) {          log.i ("test", "Input value:" +x) ;    }}

  

Package Com.example.ndktest;import Android.app.activity;import Android.os.bundle;import android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.toast;public Class Mainactivity extends Activity {public native String hello (); @Overrideprotected void OnCreate (Bundle savedinstancestate ) {super.oncreate (savedinstancestate); Setcontentview (R.layout.fragment_main); Button tx= (button) Findviewbyid (r.id.test) Tx.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {Jniprovideer jniprovideer=new jniprovideer (); String result= "";//result=jniprovideer.hello ();//int Add=jniprovideer.add (4, 5);//result=add+ "";//int[] intarray= Jniprovideer.getintarray (New int[]{3,5,5,4});//for (int i = 0; i < intarray.length; i++) {//result+=intarray[i];//}// Result=jniprovideer.sayhello ("say:");//jniprovideer.getjavamethodforgetstring ();// Jniprovideer.getjavamethodforgetadd (); Jniprovideer.getjavamethodforgetvoidmethod ();//Toast.makeTExt (Getapplicationcontext (), result, 0). Show ();}});}} 

  

JNI Learning 2:android calls the C language method and calls the Android method with C language

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.