Android's NDK Learning (1)

Source: Internet
Author: User

Android NDK Learning (1) before learning for some time the NDK, always thought to summarize. The NDK makes it easy to communicate between Java and C + + code. A reasonable grasp of the use of the NDK can improve the efficiency of application operations. So for those who learn anndroid development, the NDK is a must-have tool. I was a little excited when I started to study. A little scared, excited because I learned the C + + language before. To be able to combine what you've learned, to feel that you can do something better, to be afraid of the big God around you before you say the NDK is one of the most difficult things in Android development. However, I still find a book, read the video, find some electronic materials, and began to learn the path of the NDK!
One, the first program Hello World relative, using the NDK to implement a large number of native methods and to synchronize them with the Java class is very easy to become a tedious task.

You need to create a new Android project first. Then declare a native method in the main function, code such as the following

public class Mainactivity extends  Activity {public static native String test ();    @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);                }

Then use the command line, start-cmd, switch to the project's SRC folder and then run the command such as the following:
Javah-d. /jni the package name. Mainactivity
When you refresh the project, you'll find a JNI directory with a. h file open, which is a C-header file.
/* Don't EDIT this file-it are machine generated */#include <jni.h>/* Header for class Com_example_exercise_mainac tivity */#ifndef _included_com_example_exercise_mainactivity#define _included_com_example_exercise_mainactivity# ifdef __cplusplusextern "C" {#endif #undef com_example_exercise_mainactivity_mode_private#define com_example_ Exercise_mainactivity_mode_private 0l#undef Com_example_exercise_mainactivity_mode_world_readable#define Com_ Example_exercise_mainactivity_mode_world_readable 1l#undef Com_example_exercise_mainactivity_mode_world_ Writeable#define com_example_exercise_mainactivity_mode_world_writeable 2l#undef Com_example_exercise_ Mainactivity_mode_append#define com_example_exercise_mainactivity_mode_append 32768L#undef Com_example_exercise_ Mainactivity_mode_multi_process#define com_example_exercise_mainactivity_mode_multi_process 4L#undef Com_example_ Exercise_mainactivity_mode_enable_write_ahead_logging#define Com_example_exercise_mainactivity_mode_enable_ Write_ahead_logging 8l#undef Com_example_exercise_mainactivity_bind_auto_create#define Com_example_exercise_mainactivity_ Bind_auto_create 1l#undef Com_example_exercise_mainactivity_bind_debug_unbind#define Com_example_exercise_ Mainactivity_bind_debug_unbind 2l#undef Com_example_exercise_mainactivity_bind_not_foreground#define Com_example_ Exercise_mainactivity_bind_not_foreground 4l#undef com_example_exercise_mainactivity_bind_above_client#define com _example_exercise_mainactivity_bind_above_client 8l#undef Com_example_exercise_mainactivity_bind_allow_oom_ Management#define com_example_exercise_mainactivity_bind_allow_oom_management 16L#undef Com_example_exercise_ Mainactivity_bind_waive_priority#define com_example_exercise_mainactivity_bind_waive_priority 32L#undef Com_ Example_exercise_mainactivity_bind_important#define com_example_exercise_mainactivity_bind_important 64L#undef Com_example_exercise_mainactivity_bind_adjust_with_activity#define Com_example_exercise_mainactivity_bind_ Adjust_with_activity 128l#undef Com_example_exercise_mainactivity_context_include_code#define Com_example_exercise_mainactivity_ Context_include_code 1l#undef Com_example_exercise_mainactivity_context_ignore_security#define Com_example_ Exercise_mainactivity_context_ignore_security 2l#undef com_example_exercise_mainactivity_context_restricted# Define com_example_exercise_mainactivity_context_restricted 4l#undef Com_example_exercise_mainactivity_result_ Canceled#define com_example_exercise_mainactivity_result_canceled 0l#undef Com_example_exercise_mainactivity_ Result_ok#define Com_example_exercise_mainactivity_result_ok-1l#undef Com_example_exercise_mainactivity_result_ First_user#define Com_example_exercise_mainactivity_result_first_user 1l#undef Com_example_exercise_MainActivity_ Default_keys_disable#define com_example_exercise_mainactivity_default_keys_disable 0L#undef Com_example_exercise_ Mainactivity_default_keys_dialer#define Com_example_exercise_mainactivity_default_keys_dialer 1L#undef Com_ Example_exErcise_mainactivity_default_keys_shortcut#define Com_example_exercise_mainactivity_default_keys_shortcut 2L# undef Com_example_exercise_mainactivity_default_keys_search_local#define Com_example_exercise_mainactivity_ Default_keys_search_local 3l#undef Com_example_exercise_mainactivity_default_keys_search_global#define Com_    Example_exercise_mainactivity_default_keys_search_global 4l/* * class:com_example_exercise_mainactivity * Method: Test * Signature: () ljava/lang/string; */jniexport jstring jnicall java_com_example_exercise_mainactivity_test (jnienv *, jclass);/* * CLASS:COM_EXAMPLE_EX ercise_mainactivity * Method:updatefile * Signature: (ljava/lang/string;) V */<pre name= "code" class= "Java" >jnica LL Java_com_example_exercise_mainactivity_updatefile (jnienv *, Jclass, jstring)
#ifdef __cplusplus} #endif #endif

The code is very long. But we just want to see
Jnicall java_com_example_exercise_mainactivity_updatefile  (jnienv *, Jclass, jstring)
This is a method generated from the native method that we started with in mainactivity definition.

With a header file, we'll be able to start writing a. c file. That is, implement the file, create a new file MAIN.C. Then enter the code such as the following

#include <stdio.h> #include <stdlib.h>jniexport jstring jnicall java_com_example_exercise_mainactivity_ Test (JNIENV * env, Jobject obj) {return (*env)->newstringutf (env, "Hello world!");}

Returns a string that is the code that Java interacts with C.

But now it can't be done directly, but also to create a new Android.mk file to configure the project, such as the following code:
Local_path: =$ (call My-dir) include $ (clear_vars) local_module    : = mainlocal_src_files: = Main.cinclude $ (build_ Shared_library)

Well, then it's in the mainactivity. Code such as the following
public class Mainactivity extends  Activity {public static native String test ();     @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        TextView t = (TextView) Findviewbyid (R.id.jnitextview);        T.settext (Test ());           }    static {System.loadlibrary ("main");}    }

The import library is used
  static {System.loadlibrary ("main");}
Main is a name we have configured in Android.mk, which is now ready to be compiled to generate so files only. We open cmd and switch to the project folder and execute ndk-build. The middle is a minus, not an underscore, refresh the project can see the Libs in a folder and a libmain.so file inside, this time you can execute the project!

Assuming there is no accident, there will be HelloWorld on the mobile phone frequency screen.

Two. Print log print log is the only one that must be mastered. So here is how to configure, the first is to configure the Android.mk file. Add a line of code local_ldlibs + =-llog
The complete android.mk code such as the following
Local_path: =$ (call My-dir) include $ (clear_vars) local_module    : = mainlocal_src_files: = main.clocal_ldlibs    + = -lloginclude $ (build_shared_library)

Then add the header file to the implementation file #include<android/log.h> and the macro defines the type of log to print # 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__))
Use Logi () or LOGW in your code. Execute the program and then you will be able to print the log! More specifically, you can see the NDK chapter in the Java API documentation.

Three, summed up just started to learn JNI, to configure this to configure that is very troublesome, but wrote a helloworld after the configuration is like that, everything at the beginning difficult Ah! Believe that learning in the back will become more and more difficult. But it will be more and more interesting, hope to continue to refuel!

Android's NDK Learning (1)

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.