This section learns to call the Java language using the C language. In life, for example, some of our underlying hardware must be written in C, when some of the values returned by C are displayed on the interface, such as using JNI. This allows you to display the value returned by C on the interface.
This section simulates the value returned by the sensor, displays the sensitivity through the progress bar, and then displays it to the interface.
1: The interface layout is more than enough to say. There are 2 buttons in it, one for turning on the monitor, one for turning off the monitor, one for the progress bar
The 2:activity code is as follows:
Start monitoring buttonpublic void start (View v) {startmonitor ();} Stop monitoring buttonpublic void Stop (View v) {stopmonitor ();} Local method to start monitoring and stop monitoring public native void StartMonitor ();p ublic native void Stopmonitor ();//c language call Java Refresh progress bar function public void Showvalue (int progress) {bar.setprogress (progress);}
3: Local JNI code
#include <jni.h> #include <stdio.h> #include <stdlib.h>int monitor = 1;//randomly generated value int getpressure () { return rand ()%100; /* Class: com_demo_ccalljava_mainactivity * Method: startmonitor * Signature: () V */jniexport void Jnicall Java _com_demo_ccalljava_mainactivity_startmonitor (jnienv *env, Jobject obj) {while (monitor) {//get current pressure value int value = Getpressure ();//Use reflection to find a way to play Show method//1: Find bytecode file Jclass Cclass = (*env)->findclass (env, "com/demo/ccalljava/mainactivity" );//2: Find Method Id//show is the name of the calling Java method, (i) v is the signature of the method Jmethodid Methodid = (*env)->getmethodid (Env,cclass, "Showvalue", "(i) V ");//3: Call Method (*ENV)->callvoidmethod (env, obj, methodid, value); sleep (1);}} /* Class: com_demo_ccalljava_mainactivity * Method: stopmonitor * Signature: () V */jniexport void Jnicall Java_ Com_demo_ccalljava_mainactivity_stopmonitor (jnienv *env, jobject obj) {monitor = 0;}
3: Load Dynamic Library
Static{system.loadlibrary ("Ccalljava");}
4: Start monitoring display:
When you press start, there is a stuck GUI, which is because StartMonitor is running on the main thread, so stuck GUI
5: Modify, StartMonitor run on child thread
Start monitoring buttonpublic void start (View v) {Thread thread = new Thread () {@Overridepublic void run () {startmonitor ();}}; Thread.Start ();}
6: Run again to display the effect:
can be displayed normally.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Learning JNI, calling the Java language using C