Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Trước khi bắt đầu
Hướng dẫn này giả định rằng bạn đã quen thuộc với các khái niệm vốn có trong chương trình gốc và trong quá trình phát triển Android.
Giới thiệu
Phần này đưa ra nội dung giải thích tổng thể về cách thức hoạt động của NDK. Android NDK là một bộ công cụ cho phép bạn nhúng C hoặc C++ (“mã gốc”) vào ứng dụng Android. Khả năng sử dụng mã gốc trong ứng dụng Android có thể đặc biệt hữu ích cho các nhà phát triển muốn thực hiện một hoặc nhiều việc sau:
Chuyển ứng dụng giữa các nền tảng.
Sử dụng lại thư viện hiện có hoặc cung cấp thư viện riêng cho phép sử dụng lại.
Tăng hiệu suất trong một số trường hợp nhất định, đặc biệt các trường hợp nặng về điện toán như trò chơi.
Cách thức hoạt động
Phần này giới thiệu các thành phần chính dùng để xây dựng ứng dụng gốc dành cho Android, đồng thời mô tả quy trình xây dựng và đóng gói ứng dụng.
Các thành phần chính
Khi xây dựng ứng dụng, bạn nắm rõ về các thành phần sau:
Thư viện chia sẻ gốc: NDK xây dựng các thư viện này hoặc các tệp .so qua mã nguồn C/C++ của bạn.
Thư viện tĩnh gốc: NDK cũng có thể xây dựng các thư viện tĩnh hoặc các tệp .a mà bạn có thể liên kết với các thư viện khác.
Giao diện gốc của Java (Java Native Interface – JNI): JNI là giao diện mà qua đó các thành phần Java và C++ giao tiếp với nhau. Hướng dẫn này giả định rằng bạn đã có kiến thức về JNI. Bạn có thể tham khảo nội dung Thông số kỹ thuật của giao diện gốc Java để biết thêm thông tin.
Giao diện nhị phân của ứng dụng (Application Binary Interface – ABI): ABI xác định chính xác cách mã máy của ứng dụng tương tác với hệ thống khi chạy. NDK xây dựng các tệp .so dựa trên những định nghĩa này. Mỗi ABI lại có kiến trúc riêng: NDK cung cấp tính năng hỗ trợ ABI cho ARM 32-bit, AArch64, x86 và x86-64. Để biết thêm thông tin, hãy xem nội dung ABI Android.
Sau đây là quy trình chung về việc phát triển một ứng dụng gốc dành cho Android:
Thiết kế ứng dụng của bạn, quyết định phần nào cần triển khai trong Java và phần nào cần triển khai dưới dạng mã gốc.
Tạo một Dự án ứng dụng Android như bạn thực hiện với mọi dự án Android khác.
Nếu bạn đang viết một ứng dụng chỉ dùng mã gốc, hãy khai báo lớp nativeActivity trong AndroidManifest.xml. Để biết thêm thông tin, hãy xem nội dung Hoạt động gốc và ứng dụng gốc.
Tạo một tệp Android.mk mô tả thư viện gốc, bao gồm cả tên, các cờ, thư viện liên kết và tệp nguồn được biên dịch trong thư mục "JNI".
Nếu muốn, bạn có thể tạo một tệp Application.mk định cấu hình ABI mục tiêu, chuỗi công cụ, chế độ phát hành/gỡ lỗi và STL. Đối với mọi giá trị bạn không chỉ định trong số này, giá trị mặc định sau đây sẽ được sử dụng, lần lượt như sau:
ABI: tất cả ABI không còn được dùng nữa
Chế độ: Phát hành
STL: hệ thống
Đặt nguồn mã gốc vào thư mục jni của dự án.
Sử dụng ndk-build để biên dịch thư viện gốc (.so, .a).
Xây dựng thành phần Java, tạo tệp thực thi .dex.
Đóng gói mọi thứ vào một tệp APK, chứa .so, .dex và các tệp khác cần thiết để ứng dụng của bạn chạy được.
Hoạt động gốc và ứng dụng gốc
SDK Android cung cấp một lớp trợ giúp (NativeActivity) cho phép bạn viết một hoạt động hoàn toàn bằng mã gốc. NativeActivity xử lý thông tin giao tiếp giữa khung Android và mã gốc, vì vậy bạn không phải tạo lớp con hoặc gọi phương thức. Bạn chỉ cần khai báo rằng ứng dụng của bạn là ứng dụng gốc trong tệp AndroidManifest.xml rồi bắt đầu tạo ứng dụng gốc.
Ứng dụng Android sử dụng NativeActivity vẫn sẽ chạy trong máy ảo của riêng ứng dụng đó và chạy trong hộp cát qua các ứng dụng khác. Do đó, bạn vẫn có thể truy cập API khung Android thông qua JNI. Trong một số trường hợp (chẳng hạn như đối với các cảm biến, sự kiện đầu vào và nội dung), NDK cung cấp giao diện gốc mà bạn có thể sử dụng thay vì phải gọi trên JNI. Để biết thêm thông tin về tính năng hỗ trợ đó, hãy xem nội dung API gốc.
Bất kể có đang phát triển hoạt động gốc hay không, bạn nên tạo dự án bằng các công cụ xây dựng Android truyền thống. Phương pháp này sẽ giúp đảm bảo việc tạo và đóng gói ứng dụng Android với cấu trúc chính xác.
Android NDK cung cấp cho bạn hai lựa chọn để triển khai hoạt động gốc:
Tiêu đề native_activity.h khai báo phiên bản gốc của lớp nativeActivity. Tiêu đề này chứa giao diện gọi lại và các cấu trúc dữ liệu cần thiết để tạo hoạt động gốc. Vì luồng chính của ứng dụng của bạn xử lý các lệnh gọi lại, nên các phương thức triển khai lệnh gọi lại của bạn đều không được chặn. Nếu các phương thức triển khai này chặn, bạn có thể gặp lỗi ANR (Ứng dụng không phản hồi) vì luồng chính không phản hồi cho đến khi lệnh gọi lại trở về.
Tệp android_native_app_glue.h khai báo một thư viện trình trợ giúp tĩnh được xây dựng trên giao diện native_activity.h. Thư viện này tạo ra một luồng khác để xử lý các lệnh gọi lại hoặc sự kiện đầu vào trong vòng lặp sự kiện. Việc di chuyển các sự kiện này sang một luồng riêng biệt sẽ ngăn mọi lệnh gọi lại chặn luồng chính của bạn.
Nguồn <ndk_root>/sources/android/native_app_glue/android_native_app_glue.c cũng có sẵn, cho phép bạn sửa đổi phương thức triển khai.
Để biết thêm thông tin về cách sử dụng thư viện tĩnh này, hãy kiểm tra mẫu ứng dụng hoạt động gốc và tài liệu tương ứng. Bạn cũng có thể đọc thêm trong các ghi chú ở tệp <ndk_root>/sources/android/native_app_glue/android_native_app_glue.h.
Thuộc tính android:value của thẻ meta-data sẽ chỉ định tên của thư viện chia sẻ chứa điểm truy cập vào ứng dụng (chẳng hạn như C/C++main), bỏ qua tiền tố lib và hậu tố .so của tên thư viện.
Tạo một tệp dành cho hoạt động gốc của bạn roofi triển khai hàm có tên trong biến AnativeActivity_onCreate. Ứng dụng gọi hàm này khi hoạt động gốc bắt đầu. Hàm này (tương tự như hàm main trong C/C++) nhận một con trỏ đến một cấu trúc ANativeActivity có chứa các con trỏ hàm đến nhiều phương thức triển khai lệnh gọi lại mà bạn cần viết. Thiết lập các con trỏ hàm gọi lại hiện hành trong ANativeActivity->callbacks thành phương thức triển khai của các lệnh gọi lại.
Thiết lập trường ANativeActivity->instance thành địa chỉ của mọi thực thể của dữ liệu cụ thể mà bạn muốn sử dụng.
Triển khai mọi việc khác mà bạn muốn hoạt động của mình thực hiện khi khởi động.
Triển khai các lệnh gọi lại còn lại mà bạn đã thiết lập trong ANativeActivity->callbacks. Để biết thêm thông tin về thời điểm gọi lệnh gọi lại, hãy xem nội dung Quản lý vòng đời hoạt động.
Phát triển phần còn lại của ứng dụng.
Tạo Android.mk file trong thư mục jni/ của dự án để mô tả cho hệ thống xây dựng về mô-đun gốc của bạn. Để biết thêm thông tin, hãy xem nội dung Android.mk.
Sau khi bạn có tệp Android.mk, hãy biên dịch mã gốc bằng lệnh ndk-build.
cd<path>/<to>/<project>
$NDK/ndk-build
Tạo bản dựng và cài đặt dự án Android của bạn như bình thường. Nếu mã gốc của bạn nằm trong thư mục jni/, thì tập lệnh bản dựng sẽ tự động đóng gói (các) tệp .so được tạo qua mã gốc đó vào tệp APK.
Nội dung và mã mẫu trên trang này phải tuân thủ các giấy phép như mô tả trong phần Giấy phép nội dung. Java và OpenJDK là nhãn hiệu hoặc nhãn hiệu đã đăng ký của Oracle và/hoặc đơn vị liên kết của Oracle.
Cập nhật lần gần đây nhất: 2025-07-27 UTC.
[null,null,["Cập nhật lần gần đây nhất: 2025-07-27 UTC."],[],[],null,["# Concepts\n\nBefore you begin\n----------------\n\nThis guide assumes that you are already familiar with concepts inherent in\nnative programming and in [Android development](/develop).\n\nIntroduction\n------------\n\nThis section provides a high-level explanation of how the NDK works. The Android NDK is a set of\ntools allowing you to embed C or C++ (\"native code\") into your Android apps. The ability to use\nnative code in Android apps can be particularly useful to developers who wish to do one or more of\nthe following:\n\n- Port their apps between platforms.\n- Reuse existing libraries, or provide their own libraries for reuse.\n- Increase performance in certain cases, particularly computationally intensive ones like games.\n\nHow it works\n------------\n\nThis section introduces the main components used in building a native\napplication for Android, and goes on to describe the process of building and\npackaging.\n\n### Main components\n\nYou should have an understanding of the following components as you build your\napp:\n\n- Native shared libraries: The NDK builds these libraries, or `.so` files, from\n your C/C++ source code.\n\n- Native static libraries: The NDK can also build static libraries, or `.a`\n files, which you can link into other libraries.\n\n- Java Native Interface (JNI): The JNI is the interface via which the Java and\n C++ components talk to one another. This guide assumes knowledge of the JNI;\n for information about it, consult the [Java Native Interface Specification](http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html).\n\n- Application Binary Interface (ABI): The ABI defines exactly how your app's\n machine code is expected to interact with the system at runtime. The NDK\n builds `.so` files against these definitions. Different ABIs correspond to\n different architectures: The NDK includes ABI support for 32-bit ARM, AArch64,\n x86, and x86-64. For more information, see [Android\n ABIs](/ndk/guides/abis).\n\n- Manifest: If you are writing an app with no Java component to it, you must\n declare the [NativeActivity](/reference/android/app/NativeActivity) class in the\n [manifest](/guide/topics/manifest/manifest-intro). See [Use the\n native_activity.h interface](#na) for more detail on how to do this.\n\n### Flow\n\nThe general flow for developing a native app for Android is as follows:\n\n1. Design your app, deciding which parts to implement in Java, and which parts\n to implement as native code.\n\n | **Note:** While it is possible to completely avoid Java, you are likely to find the Android Java framework useful for tasks including controlling the display and UI.\n2. Create an Android app Project as you would for any other Android project.\n\n3. If you are writing a native-only app, declare the [NativeActivity](/reference/android/app/NativeActivity) class in\n `AndroidManifest.xml`. For more information, see the [Native activities and\n applications](#naa).\n\n4. Create an `Android.mk` file describing the native library, including name,\n flags, linked libraries, and source files to be compiled in the \"JNI\"\n directory.\n\n5. Optionally, you can create an `Application.mk` file configuring the target\n ABIs, toolchain, release/debug mode, and STL. For any of these that you do\n not specify, the following default values are used, respectively:\n\n - ABI: all non-deprecated ABIs\n - Mode: Release\n - STL: system\n6. Place your native source under the project's `jni` directory.\n\n7. Use ndk-build to compile the native (`.so`, `.a`) libraries.\n\n8. Build the Java component, producing the executable `.dex` file.\n\n9. Package everything into an APK file, containing `.so`, `.dex`, and other\n files needed for your app to run.\n\nNative activities and applications\n----------------------------------\n\nThe Android SDK provides a helper class, [NativeActivity](/reference/android/app/NativeActivity), that allows you to\nwrite a completely native activity. [NativeActivity](/reference/android/app/NativeActivity) handles the communication\nbetween the Android framework and your native code, so you do not have to\nsubclass it or call its methods. All you need to do is declare your application\nto be native in your `AndroidManifest.xml` file, and begin creating your native\napplication.\n\nAn Android application using [NativeActivity](/reference/android/app/NativeActivity) still runs in its own virtual\nmachine, sandboxed from other applications. You can therefore still access\nAndroid framework APIs through the JNI. In certain cases, such as for sensors,\ninput events, and assets, the NDK provides native interfaces that you can use\ninstead of having to call across the JNI. For more information about such\nsupport, see [Native APIs](/ndk/guides/stable_apis).\n\nRegardless of whether or not you are developing a native activity, we recommend\nthat you create your projects with the traditional Android build tools. Doing so\nhelps ensure building and packaging of Android applications with the correct\nstructure.\n\nThe Android NDK provides you with two choices to implement your native activity:\n\n- The [native_activity.h](/ndk/reference/native__activity_8h) header defines the native version of the [NativeActivity](/reference/android/app/NativeActivity) class. It contains the callback interface and data structures that you need to create your native activity. Because the main thread of your application handles the callbacks, your callback implementations must not be blocking. If they block, you might receive ANR (Application Not Responding) errors because your main thread is unresponsive until the callback returns.\n- The `android_native_app_glue.h` file defines a static helper library built on top of the [native_activity.h](/ndk/reference/native__activity_8h) interface. It spawns another thread, which handles things such as callbacks or input events in an event loop. Moving these events to a separate thread prevents any callbacks from blocking your main thread.\n\nThe `\u003cndk_root\u003e/sources/android/native_app_glue/android_native_app_glue.c`\nsource is also available, allowing you to modify the implementation.\n\nFor more information on how to use this static library, examine the\nnative-activity sample application and its documentation. Further reading is\nalso available in the comments in the\n`\u003cndk_root\u003e/sources/android/native_app_glue/android_native_app_glue.h`\nfile.\n\n### Use the native_activity.h interface\n\nTo implement a native activity with the [native_activity.h](/ndk/reference/native__activity_8h) interface:\n\n1. Create a `jni/` directory in your project's root directory. This directory\n stores all of your native code.\n\n2. Declare your native activity in the `AndroidManifest.xml` file.\n\n Because your application has no Java code, set `android:hasCode` to `false`. \n\n \u003capplication android:label=\"@string/app_name\" android:hasCode=\"false\"\u003e\n\n You must set the `android:name` attribute of the activity tag to\n [NativeActivity](/reference/android/app/NativeActivity). \n\n \u003cactivity android:name=\"android.app.NativeActivity\"\n android:label=\"@string/app_name\"\u003e\n\n | **Note:** You can subclass [NativeActivity](/reference/android/app/NativeActivity). If you do, use the name of the subclass instead of [NativeActivity](/reference/android/app/NativeActivity).\n\n The `android:value` attribute of the `meta-data` tag specifies the name of\n the shared library containing the entry point to the application (such as\n C/C++ `main`), omitting the `lib` prefix and `.so` suffix from the library\n name. \n\n \u003cmanifest\u003e\n \u003capplication\u003e\n \u003cactivity\u003e\n \u003cmeta-data android:name=\"android.app.lib_name\"\n android:value=\"native-activity\" /\u003e\n \u003cintent-filter\u003e\n \u003caction android:name=\"android.intent.action.MAIN\" /\u003e\n \u003ccategory android:name=\"android.intent.category.LAUNCHER\" /\u003e\n \u003c/intent-filter\u003e\n \u003c/activity\u003e\n \u003c/application\u003e\n \u003c/manifest\u003e\n\n3. Create a file for your native activity, and implement the function named in\n the [ANativeActivity_onCreate](/ndk/reference/group___native_activity#ga02791d0d490839055169f39fdc905c5e) variable. The app calls this function when the\n native activity starts. This function, analogous to `main` in C/C++, receives\n a pointer to an [ANativeActivity](/ndk/reference/struct_a_native_activity) structure, which contains function pointers\n to the various callback implementations that you need to write. Set the\n applicable callback function pointers in `ANativeActivity-\u003ecallbacks` to\n the implementations of your callbacks.\n\n4. Set the `ANativeActivity-\u003einstance` field to the address of any instance of\n specific data that you want to use.\n\n5. Implement anything else that you want your activity to do upon starting.\n\n6. Implement the rest of the callbacks that you set in\n `ANativeActivity-\u003ecallbacks`. For more information on when the callbacks are\n called, see [Managing the Activity Lifecycle](/training/basics/activity-lifecycle).\n\n7. Develop the rest of your application.\n\n8. Create an `Android.mk file` in the `jni/` directory of your project to\n describe your native module to the build system. For more information, see\n [Android.mk](/ndk/guides/android_mk).\n\n9. Once you have an [Android.mk](/ndk/guides/android_mk) file, compile your native code using the\n `ndk-build` command.\n\n cd \u003cpath\u003e/\u003cto\u003e/\u003cproject\u003e\n $NDK/ndk-build\n\n10. Build and install your Android project as usual. If your native code is in\n the `jni/` directory, the build script automatically packages the `.so`\n file(s) built from it into the APK.\n\nAdditional sample code\n----------------------\n\nTo download NDK samples, see [NDK Samples](https://github.com/android/ndk-samples)."]]