Tích hợp Asset Delivery (gốc)

Hãy làm theo các bước trong hướng dẫn này để truy cập vào gói tài sản của ứng dụng từ mã C và C++.

Bạn có thể xem mã tích hợp mẫu trên GitHub.

Tích hợp đối với ứng dụng gốc

Hãy làm theo các bước sau đây để tích hợp Play Asset Delivery vào tệp Android App Bundle của dự án. Bạn không cần sử dụng Android Studio để thực hiện các bước này.

  1. Cập nhật phiên bản trình bổ trợ Android cho Gradle trong tệp build.gradle của dự án lên phiên bản 4.0.0 trở lên.

  2. Trong thư mục cấp cao nhất của dự án, tạo thư mục cho gói tài sản. Tên thư mục này được dùng làm tên gói tài sản. Tên gói tài sản phải bắt đầu bằng một chữ cái và chỉ được chứa chữ cái, số và dấu gạch dưới.

  3. Trong thư mục gói tài sản, hãy tạo tệp build.gradle rồi thêm mã sau đây. Hãy nhớ chỉ định tên của gói tài sản và chỉ một loại hình phân phối:

    // In the asset pack’s build.gradle file:
    plugins {
        id 'com.android.asset-pack'
    }
    
    assetPack {
        packName = "asset-pack-name" // Directory name for the asset pack
        dynamicDelivery {
            deliveryType = "[ install-time | fast-follow | on-demand ]"
        }
    }
    
  4. Trong tệp build.gradle của ứng dụng thuộc dự án, hãy thêm tên của từng gói tài sản vào dự án như trình bày dưới đây:

    // In the app build.gradle file:
    android {
        ...
        assetPacks = [":asset-pack-name", ":asset-pack2-name"]
    }
    
  5. Trong tệp settings.gradle của dự án, hãy đưa tất cả gói tài sản vào dự án như trình bày dưới đây:

    // In the settings.gradle file:
    include ':app'
    include ':asset-pack-name'
    include ':asset-pack2-name'
    
  6. Trong thư mục gói tài sản, hãy tạo thư mục con sau đây: src/main/assets.

  7. Đặt tài sản vào thư mục src/main/assets. Ở đây, bạn cũng có thể tạo thư mục con. Lúc này, cấu trúc thư mục cho ứng dụng sẽ có dạng như sau:

    • build.gradle
    • settings.gradle
    • app/
    • asset-pack-name/build.gradle
    • asset-pack-name/src/main/assets/your-asset-directories
  8. Xây dựng Android App Bundle bằng Gradle. Vào lúc này trong gói ứng dụng đã tạo, thư mục cấp cơ sở gồm những phần tử sau:

    • asset-pack-name/manifest/AndroidManifest.xml: Định cấu hình chế độ phân phối và giá trị nhận dạng của gói tài sản
    • asset-pack-name/assets/your-asset-directories: Thư mục chứa tất cả các tài sản được phân phối trong gói tài sản

    Gradle sẽ tạo tệp kê khai cho mỗi gói tài sản và xuất ra thư mục assets/ cho bạn.

  9. (Không bắt buộc) Định cấu hình gói ứng dụng để hỗ trợ nhiều định dạng nén kết cấu.

Tích hợp với Thư viện Play Asset Delivery

Bạn sẽ triển khai API này theo loại phân phối của gói tài sản mà bạn muốn truy cập. Các bước này được thể hiện trong sơ đồ quy trình sau.

Sơ đồ quy trình gói tài sản cho mã gốc

Hình 1. Sơ đồ quy trình truy cập gói tài sản

SDK gốc của Play Core cung cấp tệp tiêu đề C play/asset_pack.h để yêu cầu gói tài sản, quản lý tệp đã tải xuống và truy cập vào các tài sản đó.

Thiết lập môi trường phát triển cho SDK gốc Play Core

Download Play Core Native SDK

Before downloading, you must agree to the following terms and conditions.

Terms and Conditions

Last modified: September 24, 2020
  1. By using the Play Core Software Development Kit, you agree to these terms in addition to the Google APIs Terms of Service ("API ToS"). If these terms are ever in conflict, these terms will take precedence over the API ToS. Please read these terms and the API ToS carefully.
  2. For purposes of these terms, "APIs" means Google's APIs, other developer services, and associated software, including any Redistributable Code.
  3. “Redistributable Code” means Google-provided object code or header files that call the APIs.
  4. Subject to these terms and the terms of the API ToS, you may copy and distribute Redistributable Code solely for inclusion as part of your API Client. Google and its licensors own all right, title and interest, including any and all intellectual property and other proprietary rights, in and to Redistributable Code. You will not modify, translate, or create derivative works of Redistributable Code.
  5. Google may make changes to these terms at any time with notice and the opportunity to decline further use of the Play Core Software Development Kit. Google will post notice of modifications to the terms at https://developer.android.com/guide/playcore/license. Changes will not be retroactive.
Download Play Core Native SDK

play-core-native-sdk-1.14.0.zip

  1. Thực hiện một trong hai cách sau:

    • Cài đặt Android Studio phiên bản 4.0 trở lên. Sử dụng giao diện người dùng Trình quản lý SDK để cài đặt Nền tảng SDK Android phiên bản 10.0 (API cấp 29).
    • Cài đặt công cụ dòng lệnh của SDK Android và sử dụng sdkmanager để cài đặt Nền tảng SDK Android phiên bản 10.0 (API cấp 29).
  2. Chuẩn bị Android Studio cho việc phát triển bằng mã gốc bằng cách dùng Trình quản lý SDK để cài đặt CMake và Bộ phát triển mã gốc Android (NDK) mới nhất. Để biết thêm thông tin về việc tạo hoặc nhập các dự án gốc, xem Bắt đầu với NDK.

  3. Tải tệp zip xuống và giải nén cùng dự án của bạn.

    Đường liên kết để tải xuống Kích thước Giá trị tổng kiểm SHA-256
    36 MiB 782a8522d937848c83a715c9a258b95a3ff2879a7cd71855d137b41c00786a5e
  4. Cập nhật tệp build.gradle của ứng dụng như minh hoạ dưới đây:

    Groovy

        // App build.gradle
    
        plugins {
          id 'com.android.application'
        }
    
        // Define a path to the extracted Play Core SDK files.
        // If using a relative path, wrap it with file() since CMake requires absolute paths.
        def playcoreDir = file('../path/to/playcore-native-sdk')
    
        android {
            defaultConfig {
                ...
                externalNativeBuild {
                    cmake {
                        // Define the PLAYCORE_LOCATION directive.
                        arguments "-DANDROID_STL=c++_static",
                                  "-DPLAYCORE_LOCATION=$playcoreDir"
                    }
                }
                ndk {
                    // Skip deprecated ABIs. Only required when using NDK 16 or earlier.
                    abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
                }
            }
            buildTypes {
                release {
                    // Include Play Core Library proguard config files to strip unused code while retaining the Java symbols needed for JNI.
                    proguardFile '$playcoreDir/proguard/common.pgcfg'
                    proguardFile '$playcoreDir/proguard/gms_task.pgcfg'
                    proguardFile '$playcoreDir/proguard/per-feature-proguard-files'
                    ...
                }
                debug {
                    ...
                }
            }
            externalNativeBuild {
                cmake {
                    path 'src/main/CMakeLists.txt'
                }
            }
        }
    
        dependencies {
            // Import these feature-specific AARs for each Google Play Core library.
            implementation 'com.google.android.play:app-update:2.0.0'
            implementation 'com.google.android.play:asset-delivery:2.0.0'
            implementation 'com.google.android.play:integrity:1.0.1'
            implementation 'com.google.android.play:review:2.0.0'
    
            // Import these common dependencies.
            implementation 'com.google.android.gms:play-services-tasks:18.0.2'
            implementation files("$playcoreDir/playcore-native-metadata.jar")
            ...
        }
        

    Kotlin

    // App build.gradle
    
    plugins {
        id("com.android.application")
    }
    
    // Define a path to the extracted Play Core SDK files.
    // If using a relative path, wrap it with file() since CMake requires absolute paths.
    val playcoreDir = file("../path/to/playcore-native-sdk")
    
    android {
        defaultConfig {
            ...
            externalNativeBuild {
                cmake {
                    // Define the PLAYCORE_LOCATION directive.
                    arguments += listOf("-DANDROID_STL=c++_static", "-DPLAYCORE_LOCATION=$playcoreDir")
                }
            }
            ndk {
                // Skip deprecated ABIs. Only required when using NDK 16 or earlier.
                abiFilters.clear()
                abiFilters += listOf("armeabi-v7a", "arm64-v8a", "x86", "x86_64")
            }
        }
        buildTypes {
            release {
                // Include Play Core Library proguard config files to strip unused code while retaining the Java symbols needed for JNI.
                proguardFile("$playcoreDir/proguard/common.pgcfg")
                proguardFile("$playcoreDir/proguard/gms_task.pgcfg")
                proguardFile("$playcoreDir/proguard/per-feature-proguard-files")
                ...
            }
            debug {
                ...
            }
        }
        externalNativeBuild {
            cmake {
                path = "src/main/CMakeLists.txt"
            }
        }
    }
    
    dependencies {
        // Import these feature-specific AARs for each Google Play Core library.
        implementation("com.google.android.play:app-update:2.0.0")
        implementation("com.google.android.play:asset-delivery:2.0.0")
        implementation("com.google.android.play:integrity:1.0.1")
        implementation("com.google.android.play:review:2.0.0")
    
        // Import these common dependencies.
        implementation("com.google.android.gms:play-services-tasks:18.0.2")
        implementation(files("$playcoreDir/playcore-native-metadata.jar"))
        ...
    }
    
  5. Cập nhật các tệp CMakeLists.txt của ứng dụng như bên dưới:

    cmake_minimum_required(VERSION 3.6)
    
    ...
    
    # Add a static library called “playcore” built with the c++_static STL.
    include(${PLAYCORE_LOCATION}/playcore.cmake)
    add_playcore_static_library()
    
    // In this example “main” is your native code library, i.e. libmain.so.
    add_library(main SHARED
            ...)
    
    target_include_directories(main PRIVATE
            ${PLAYCORE_LOCATION}/include
            ...)
    
    target_link_libraries(main
            android
            playcore
            ...)
    

Thu thập dữ liệu

SDK gốc của Play Core có thể thu thập một số dữ liệu liên quan đến phiên bản để cho phép Google cải thiện sản phẩm, trong đó có:

  • Tên gói của ứng dụng
  • Phiên bản gói của ứng dụng
  • Phiên bản SDK gốc của Play Core

Dữ liệu này sẽ được thu thập khi bạn tải gói ứng dụng lên Play Console. Để chọn không tham gia quá trình thu thập dữ liệu này, hãy xoá việc nhập $playcoreDir/playcore-native-metadata.jar trong tệp build.gradle.

Hãy lưu ý rằng quá trình thu thập dữ liệu này liên quan đến việc bạn sử dụng SDK gốc Play Core và việc Google sử dụng dữ liệu đã thu thập là hoạt động riêng biệt và độc lập với việc thu thập các phần phụ thuộc của thư viện được khai báo trong Gradle khi bạn tải gói ứng dụng lên Play Console.

Phân phối khi cài đặt

Các gói tài sản được định cấu hình là install-time sẽ có sẵn ngay khi khởi chạy ứng dụng. Sử dụng NDK AAssetManager API để truy cập vào các tài sản có ở chế độ này:

#include <android/asset_manager.h>
#include <android_native_app_glue.h>
...
AAssetManager* assetManager = app->activity->assetManager;
AAsset* asset = AAssetManager_open(assetManager, "asset-name", AASSET_MODE_BUFFER);
size_t assetLength = AAsset_getLength(asset);
char* buffer = (char*) malloc(assetLength + 1);
AAsset_read(asset, buffer, assetLength);

Phân phối tiếp nối nhanh và theo yêu cầu

Các mục sau đây cho biết cách khởi chạy API, cách nhận thông tin về gói tài sản trước khi tải xuống, cách gọi API để bắt đầu tải xuống và cách truy cập vào gói đã tải xuống. Các mục này áp dụng cho các gói tài sản fast-followon-demand.

Chạy ứng dụng

Luôn gọi AssetPackManager_init() để khởi chạy API gói tài sản trước khi gọi bất kỳ hàm nào khác. Hãy kiểm tra xem có mã lỗi gói tài sản hay không.

#include "play/asset_pack.h"
...
AssetPackErrorCode AssetPackManager_init(JavaVM* jvm, jobject android_context);

Ngoài ra, hãy nhớ gọi các hàm sau đây trong onPause()onResume() của ANativeActivityCallbacks:

Xem thông tin tải xuống về gói tài sản

Các ứng dụng bắt buộc phải công bố kích thước của tệp tải xuống trước khi tìm nạp gói tài sản. Hãy sử dụng hàm AssetPackManager_requestInfo() để bắt đầu yêu cầu không đồng bộ về kích thước của tệp tải xuống và liệu gói đã được tải xuống hay chưa. Sau đó, hãy sử dụng AssetPackManager_getDownloadState() để thăm dò ý kiến về trạng thái tải xuống (ví dụ: gọi hàm này một lần cho mỗi khung trong vòng lặp trò chơi). Nếu yêu cầu không thành công, hãy kiểm tra mã lỗi gói tài sản.

AssetPackErrorCode AssetPackManager_requestInfo();      // Call once
AssetPackErrorCode AssetPackManager_getDownloadState(); // Call once per frame in your game loop

Hàm AssetPackManager_getDownloadState() trả về loại mờ AssetPackDownloadState làm con trỏ đầu ra. Hãy sử dụng con trỏ này để gọi các hàm sau:

AssetPackDownloadState* state;
AssetPackErrorCode error_code = AssetPackManager_getDownloadState(asset-pack-name, &state);
AssetPackDownloadStatus status = AssetPackDownloadState_getStatus(state);
uint64_t downloadedBytes = AssetPackDownloadState_getBytesDownloaded(state);
uint64_t totalBytes = AssetPackDownloadState_getTotalBytesToDownload(state));
AssetPackDownloadState_destroy(state);

Cài đặt

Hãy sử dụng AssetPackManager_requestDownload() để bắt đầu tải gói tài sản xuống lần đầu tiên hoặc để yêu cầu hoàn tất quá trình cập nhật gói tài sản:

AssetPackErrorCode AssetPackManager_requestDownload();  // Call once
AssetPackErrorCode AssetPackManager_getDownloadState(); // Call once per frame in your game loop

Hàm AssetPackManager_getDownloadState() trả về loại mờ AssetPackDownloadState. Để biết thông tin về cách sử dụng loại này, hãy xem Nhận thông tin tải xuống.

Tài nguyên tải xuống kích thước lớn

Nếu tệp tải xuống lớn hơn 200 MB và người dùng không sử dụng Wi-Fi, thì quá trình tải xuống sẽ chỉ bắt đầu khi người dùng đồng ý rõ ràng là sẽ tiếp tục tải xuống bằng kết nối dữ liệu di động. Tương tự, nếu tệp tải xuống lớn nhưng người dùng mất Wi-Fi, thì quá trình tải xuống sẽ tạm dừng và cần có sự đồng ý rõ ràng của người dùng để tiếp tục sử dụng kết nối dữ liệu di động. Gói bị tạm dừng có trạng thái là WAITING_FOR_WIFI. Để kích hoạt quy trình thao tác trên giao diện người dùng nhằm nhắc người dùng đồng ý, hãy sử dụng các hàm sau:

Người dùng cần xác nhận

Nếu một gói có trạng thái REQUIRES_USER_CONFIRMATION, thì quá trình tải xuống sẽ không tiếp tục cho đến khi người dùng chấp nhận hộp thoại hiển thị bằng AssetPackManager_showConfirmationDialog(). Trạng thái này có thể xuất hiện nếu Play không nhận dạng được ứng dụng. Xin lưu ý rằng trong trường hợp này, việc gọi AssetPackManager_showConfirmationDialog() sẽ khiến ứng dụng được cập nhật. Sau khi cập nhật, hãy yêu cầu lại thành phần.

Truy cập gói tài sản

Bạn có thể truy cập gói tài sản bằng cách sử dụng lệnh gọi hệ thống tệp sau khi yêu cầu tải xuống đạt đến trạng thái COMPLETED. Mỗi gói tài sản được lưu trong một thư mục riêng ở bộ nhớ trong của ứng dụng. Sử dụng AssetPackManager_getAssetPackLocation() để nhận AssetPackLocation cho gói tài sản đã chỉ định. Hãy sử dụng AssetPackLocation_getStorageMethod() ở vị trí đó để xác định phương thức lưu trữ:

  • ASSET_PACK_STORAGE_APK: Gói tài sản được cài đặt dưới dạng APK. Xem phần Phân phối tại thời điểm cài đặt để truy cập vào các tài sản này.
  • ASSET_PACK_STORAGE_FILES: Sử dụng AssetPackLocation_getAssetsPath() để nhận đường dẫn tệp đến thư mục chứa tài sản hoặc để trống nếu tài sản chưa được tải xuống. Không sửa đổi các tệp đã tải xuống trong đường dẫn tệp này.
AssetPackLocation* location;

AssetPackErrorCode error_code = AssetPackManager_getAssetPackLocation(asset-pack-name, &location);

if (error_code == ASSET_PACK_NO_ERROR) {
    AssetPackStorageMethod storage_method = AssetPackLocation_getStorageMethod(location);
    const char* assets_path = AssetPackLocation_getAssetsPath(location);
    AssetPackLocation_destroy(location);
}

Sau khi bạn tìm được tài sản, hãy sử dụng các hàm như fopen hoặc ifstream để truy cập vào các tệp đó.

Các phương thức Play Core API khác

Sau đây là một số phương thức API khác mà có thể bạn muốn sử dụng trong ứng dụng.

Huỷ yêu cầu

Sử dụng AssetPackManager_cancelDownload() để huỷ yêu cầu về gói tài sản đang hoạt động. Xin lưu ý rằng yêu cầu này là một thao tác được thực hiện trên cơ sở nỗ lực tối đa.

Yêu cầu xoá

Sử dụng AssetPackManager_requestRemoval() để lên lịch xoá gói tài sản.

Các bước tiếp theo

Kiểm thử Play Asset Delivery trên thiết bị và trên Google Play.