Link Address: http://www.cnblogs.com/lknlfy/archive/2012/03/13/2394153.html
I. Overview
For most application developers, the NDK may not be very accessible, but if it involves hardware operations, it will have to use the NDK. Another reason for using the NDK is that C + + is more efficient, so we can put some time-consuming operations into the NDK.
There's a whole bunch of articles on the web that call each other about Java and C + +. But careful observation can be found, basically speaking in Java call a local method, and then by the local method directly return a parameter to Java (for example, the local method defined in Java is private int calljni (int i)). Most of the time, however, it is not the developer who actively goes to the Java layer to tune the function in the JNI to return the desired data, but rather the JNI initiative to tune the functions in Java. For the simplest example, the camera in Android, the image data is uploaded from the kernel to the Java layer, but the transfer of these data does not require the developer every time to invoke the function in the JNI to obtain, but by the JNI initiative to the Java method, This is similar to asynchronous notifications in Linux drivers.
Second, the requirements
Using the NDK to realize the mutual transfer of Java and C + +, implementing int,string,byte[] These three types of mutual transmission.
Third, the realization
In the following implementation, each time Java invokes a function in Jni, the corresponding method in Java is called back in the function instead of directly returning a parameter. Perhaps you would think that this is not always a developer to invoke the initiative, in fact, this is only to explain, in practice, the callback method in Java should be triggered by an event (non-Java layer).
New Project Mycallback, modify the Main.xml file, add 3 buttons inside, corresponding 3 types of calls and 3 TextView respectively display the data passed to Java by JNI callback Java. The complete Main.xml file is as follows:
1 <?xml version= "1.0" encoding= "Utf-8"?>
2 <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
3 android:layout_width= "Fill_parent"
4 android:layout_height= "Fill_parent"
5 android:orientation= "Vertical" >
6
7 <button
8 android:id= "@+id/intbutton"
9 android:layout_width= "Fill_parent"
Ten android:layout_height= "Wrap_content"
One android:text= "to jni an integer 1"
/>
13
<textview
Android:id= "@+id/inttextview"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
Android:text= "received integer:"
/>
20
<button
Android:id= "@+id/stringbutton"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
Android:text= "passed to jni a character a"
/>
27
<textview
Android:id= "@+id/stringtextview"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
Android:text= "Received characters:"
/>
34
<button
Android:id= "@+id/arraybutton"
PNS android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
Android:text= "passed to jni an array of 12345"
/>
41
<textview
Android:id= "@+id/arraytextview"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
android:text= "received array:"
/>
48
49
</LinearLayout>
Modify the Mycallbackactivity.java file to define a handler that is used to send a message when the JNI callback method of Java, to implement 3 button monitoring. As follows:
1 package com.nan.callback;
2
3 Import android.app.Activity;
4 Import Android.os.Bundle;
5 Import Android.os.Handler;
6 Import Android.os.Message;
7 Import Android.view.View;
8 Import Android.widget.Button;
9 Import Android.widget.TextView;
10
11
public class Mycallbackactivity extends Activity
13 {
+ private Button Intbutton = null;
The private Button Stringbutton = null;
Private Button Arraybutton = null;
+ private TextView Inttextview = null;
Private TextView Stringtextview = null;
Private TextView Arraytextview = null;
20
$ private Handler Mhandler = null;
22
23
/** called when the activity is first created. */
@Override
public void OnCreate (Bundle savedinstancestate)
27 {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
30
Intbutton = (Button) This.findviewbyid (R.id.intbutton);
32//Register button Monitor
Intbutton.setonclicklistener (New Clicklistener ());
Stringbutton = (Button) This.findviewbyid (R.id.stringbutton);
35//Register button Monitor
Stringbutton.setonclicklistener (New Clicklistener ());
PNS Arraybutton = (Button) This.findviewbyid (R.id.arraybutton);
38//Register button Monitor
Arraybutton.setonclicklistener (New Clicklistener ());
40
Inttextview = (TextView) This.findviewbyid (R.id.inttextview);
Stringtextview = (TextView) This.findviewbyid (R.id.stringtextview);
Arraytextview = (TextView) This.findviewbyid (R.id.arraytextview);
44
45//Message Processing
Mhandler = new Handler ()
47 {
@Override
$ public void Handlemessage (Message msg)
50 {
Wuyi Switch (msg.what)
52 {
53//Integral type
0:
55 {
Inttextview.settext (Msg.obj.toString ());
a break;
58}
59//String
Case 1:
61 {
Stringtextview.settext (Msg.obj.toString ());
a break;
64}
65//Array
2:
[byte[] B = (byte[]) msg.obj;
Arraytextview.settext (Byte.tostring (b[0]) +byte.tostring (b[1]) +byte.tostring (b[2]) +byte.tostring (B[3]) +byte.tostring (b[4]);
a break;
70}
71}
72
73}
74
75};
76
77
78}
79
80//Button monitoring implementation
Bayi public class Clicklistener implements View.onclicklistener
82 {
83
@Override
-public void OnClick (View v)
86 {
/TODO auto-generated Method stub
Switch (V.getid ())
89 {
Case R.id.intbutton:
91 {
92//Call a function in JNI
Calljniint (1);
94 break;
95}
R.id.stringbutton Case:
97 {
98//Call a function in JNI
Calljnistring ("Hello a");
break;
101}
102 Case R.id.arraybutton:
103 {
104//Call a function in JNI
Calljnibyte (New byte[]{1,2,3,4,5});
106 break;
107}
108}
109}
110
111}
112
113
114//Called by JNI, parameter passed in by JNI
Callbackint private void (int i)
116 {
117 Message msg = new Message ();
118//Message type
119 Msg.what = 0;
120//message content
121 Msg.obj = i;
122//Send Message
123 Mhandler.sendmessage (msg);
124}
125
126//Called by JNI, parameter passed in by JNI
127 private void callbackstring (String s)
128 {
129 Message msg = new Message ();
130//Message type
131 msg.what = 1;
132//message content
133 Msg.obj = s;
134//Send Message
135 mhandler.sendmessage (msg);
136}
137
138//Called by JNI, parameter passed in by JNI
139 private void Callbackbyte (byte[] b)
140 {
141 Message msg = new Message ();
142//Message type
143 Msg.what = 2;
144//message content
145 msg.obj = b;
146//Send Message
147 Mhandler.sendmessage (msg);
148}
149
150//local method, called by Java
151 Private native void calljniint (int i);
The private native void Calljnistring (String s);
153 private native void Calljnibyte (byte[] b);
154
155 static
156 {
157//Load local library
158 system.loadlibrary ("Myjni");
159}
160
161}
The last is the "play" of this essay, create a new Jni folder in the root of the project, add a android.mk file and a callback.c file in it, the Android.mk file is as follows:
1 Local_path: = $ (call My-dir)
3 include $ (clear_vars)
5 local_module : = Myjni
6 Local_src_files: = CALLBACK.C
8 local_ldlibs : =-llog
Include $ (build_shared_library)
The callback.c file is as follows:
1 #include <string.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <sys/ioctl.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9
Ten #include <jni.h>
#include <android/log.h>
12
#define Logi (...) (void) __android_log_print (android_log_info, "native-activity", __va_args__))
#define LOGW (...) (void) __android_log_print (Android_log_warn, "native-activity", __va_args__))
15
16
17
18/********** Transfer Integer *************
19
20 */
Jniexport void Jnicall Java_com_nan_callback_mycallbackactivity_calljniint (jnienv* env, jobject obj, jint i)
22 {
23//Find classes in Java
Jclass cls = (*env)->findclass (env, "com/nan/callback/mycallbackactivity");
25//Re-find the method in class
Jmethodid mid = (*env)->getmethodid (env, CLS, "Callbackint", "(I) V");
if (mid = = NULL)
28 {
Logi ("int error");
return;
31}
32//Print the Received data
Logi ("from Java int:%d", i);
34//callback method in Java
(*env)->callvoidmethod (env, obj, Mid, I);
36
37}
38
39/******** Transfer String *************
41 */
Jniexport void Jnicall java_com_nan_callback_mycallbackactivity_calljnistring (jnienv* env, Jobject obj, jstring s)
43 {
44//Find classes in Java
Jclass cls = (*env)->findclass (env, "com/nan/callback/mycallbackactivity");
46//Re-find the method in class
Jmethodid mid = (*env)->getmethodid (env, CLS, "Callbackstring", "(ljava/lang/string;) V");
if (mid = = NULL)
49 {
Logi ("string error");
The return;
52}
a const char *ch;
54//Get strings passed by Java
n ch = (*env)->getstringutfchars (env, S, NULL);
56//Print
Logi ("From Java string:%s", ch);
(*env)->releasestringutfchars (env, S, ch);
59//callback method in Java
(*env)->callvoidmethod (env, obj, Mid, (*env)->newstringutf (env, "hello haha"));
61
62}
63
64/******** Transfer Array (byte[]) *************
65 */
Jniexport void Jnicall Java_com_nan_callback_mycallbackactivity_calljnibyte (jnienv* env, jobject obj, JbyteArray b)
67 {
68//Find classes in Java
Jclass cls = (*env)->findclass (env, "com/nan/callback/mycallbackactivity");
70//re-find the method in class
Jmethodid mid = (*env)->getmethodid (env, CLS, "Callbackbyte", "([B) V");
if (mid = = NULL)
73 {
Logi ("byte[] error");
(a) return;
76}
77
78//Get array length
Jsize length = (*env)->getarraylength (env,b);
Logi ("Length:%d", length);
81//Get the Received data
(+) int i;
jbyte* p = (*env)->getbytearrayelements (env,b,null);
84//Print
(i=0;i<length;i++)
86 {
Logi ("%d", p[i]);
88}
89
C[5 Char];
C[0] = 1;c[1] = 2;c[2] = 3;c[3] = 4;c[4] = 5;
92//constructed array
Jbytearray Carr = (*env)->newbytearray (env,length);
94 (*ENV)->setbytearrayregion (ENV,CARR,0,LENGTH,C);
95//callback method in Java
(*env)->callvoidmethod (env, obj, Mid, Carr);
97}
Generate the appropriate libraries using Ndk-build compilation. The code is very simple, the idea at the beginning of the time has been explained, the following see the results of the operation.
Click on each of the three buttons, the effect is as follows:
And look at the Logcat output:
Two directions (java<--->jni) are visible for correct data transfer.
Attach the complete engineering code, Android2.3.
Http://files.cnblogs.com/lknlfy/my-CallEachOther.rar
Android NDK Development (1)-----Java and C invoke each other instance