Android NDK Development (2) ----- JNI Multithreading

Source: Internet
Author: User


Previous: http://www.bkjia.com/kf/201203/123039.html

I. Overview
JNI programming is quite similar to C/C ++ programming on Linux. Every time java calls a function in JNI, some JVM parameters (such as JNIEnv and jobject) are passed in ), every time JNI calls back methods in java, it must be implemented through JVM parameters. When JNI involves multithreading, there are some differences, it is to use the AttachCurrentThread () and DetachCurrentThread () functions in the subthread function, and add the Code required to callback the java method between the two functions.

Ii. Requirements
Master the JNI multi-thread programming method.

Iii. Implementation
Create a project MyThread and modify the main. xml file. There is only one Button in it, as shown below:
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/button"
9 android: layout_width = "fill_parent"
10 android: layout_height = "wrap_content"
11 android: text = "starting the JNI thread"
12/>
13
14 </LinearLayout>

Modify the MyThreadActivity. java file, implement button listening, and call the functions in JNI to start the threads in JNI, which is relatively simple, as follows:
 
1 package com. nan. thread;
2
3 import android. app. Activity;
4 import android. OS. Bundle;
5 import android. util. Log;
6 import android. view. View;
7 import android. widget. Button;
8
9 public class MyThreadActivity extends Activity
10 {
11 private Button mButton = null;
12
13/** Called when the activity is first created .*/
14 @ Override
15 public void onCreate (Bundle savedInstanceState)
16 {
17 super. onCreate (savedInstanceState );
18 setContentView (R. layout. main );
19
20 mButton = (Button) this. findViewById (R. id. button );
21 // button listening
22 mButton. setOnClickListener (new View. OnClickListener ()
23 {
24
25 @ Override
26 public void onClick (View v)
27 {
28 // TODO Auto-generated method stub
29 // call the function in JNI to start the thread in JNI
30 mainThread ();
31
32}
33 });
34 // initialize the JNI Environment
35 setJNIEnv ();
36}
37
38 // callback by the thread in JNI
39 private static void fromJNI (int I)
40 {
41 Log. v ("Java ------>", "" + I );
42}
43
44 // local method
45 private native void mainThread ();
46 private native void setJNIEnv ();
47
48 static
49 {
50 // load the dynamic library
51 System. loadLibrary ("JNIThreads ");
52}
53
54}

Compile the JNI_Thread.c file, start five sub-threads in the mainThread () function, and call back the static method fromJNI () in java in the sub-thread function () to output the number of started threads of the current subthread. The complete content is as follows:
 
1 # include <stdio. h>
2 # include <stdlib. h>
3 # include <unistd. h>
4 # include <pthread. h>
5
6 # include <jni. h>
7 # include <android/log. h>
8
9 # define LOGI (...) (void) _ android_log_print (ANDROID_LOG_INFO, "native-activity", _ VA_ARGS __))
10 # define LOGW (...) (void) _ android_log_print (ANDROID_LOG_WARN, "native-activity", _ VA_ARGS __))
11 # define LOGE (...) (void) _ android_log_print (ANDROID_LOG_ERROR, "native-activity", _ VA_ARGS __))
12
13 // Number of threads
14 # define NUMTHREADS 5
15
16 // global variable
17 JavaVM * g_jvm = NULL;
18 jobject g_obj = NULL;
19
20
21 void * thread_fun (void * arg)
22 {
23 JNIEnv * env;
24 jclass cls;
25 jmethodID mid;
26
27 // Attach main thread
28 if (* g_jvm)-> AttachCurrentThread (g_jvm, & env, NULL )! = JNI_ OK)
29 {
30 LOGE ("% s: AttachCurrentThread () failed", _ FUNCTION __);
31 return NULL;
32}
33 // find the corresponding class
34 cls = (* env)-> GetObjectClass (env, g_obj );
35 if (cls = NULL)
36 {
37 LOGE ("FindClass () Error .....");
38 goto error;
39}
40 // re-obtain the method in the class
41 mid = (* env)-> GetStaticMethodID (env, cls, "fromJNI", "(I) V ");
42 if (mid = NULL)
43 {
44 LOGE ("GetMethodID () Error .....");
45 goto error;
46}
47 // call the static method in java
48 (* env)-> CallStaticVoidMethod (env, cls, mid, (int) arg );
49
50
51 error:
52 // Detach main thread
53 if (* g_jvm)-> DetachCurrentThread (g_jvm )! = JNI_ OK)
54 {
55 LOGE ("% s: DetachCurrentThread () failed", _ FUNCTION __);
56}
57
58
59 pthread_exit (0 );
60}
61
62 // called by java to create a subthread
63 JNIEXPORT void Java_com_nan_thread_MyThreadActivity_mainThread (JNIEnv * env, jobject obj)
64 {
65 int I;
66 pthread_t pt [NUMTHREADS];
67
68 for (I = 0; I <NUMTHREADS; I ++)
69 // create a subthread
70 pthread_create (& pt [I], NULL, & thread_fun, (void *) I );
71}
72
73
74 // built the JNI environment by calling java
75 JNIEXPORT void Java_com_nan_thread_MyThreadActivity_setJNIEnv (JNIEnv * env, jobject obj)
76 {
77 // Save the global JVM for use in the Child thread
78 (* env)-> GetJavaVM (env, & g_jvm );
79 // values cannot be directly assigned (g_obj = obj)
80 g_obj = (* env)-> NewGlobalRef (env, obj );
81}
82
83
84 // This function is called by the system when the dynamic library is loaded
85 JNIEXPORT jint JNICALL JNI_OnLoad (JavaVM * vm, void * reserved)
86 {
87 JNIEnv * env = NULL;
88 jint result =-1;
89
90 // obtain the JNI version
91 if (* vm)-> GetEnv (vm, (void **) & env, JNI_VERSION_1_4 )! = JNI_ OK)
92 {
93 LOGE ("GetEnv failed! ");
94 return result;
95}
96
97 return JNI_VERSION_1_4;
98}

Finally, write the Android. mk file:
 
1 LOCAL_PATH: = $ (call my-dir)
2
3 include $ (CLEAR_VARS)
4
5 LOCAL_MODULE: = JNIThreads
6 LOCAL_SRC_FILES: = JNI_Threads.c
7
8 LOCAL_LDLIBS: =-llog
9
10 include $ (BUILD_SHARED_LIBRARY)

After the dynamic library is compiled successfully using ndk-build, run the program:



 

Click the 2 button and the LogCat output is as follows:


 

From lknlfy
 

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.