Mengintegrasikan Asset Delivery (native)

Gunakan langkah-langkah dalam panduan ini untuk mengakses paket aset aplikasi Anda dari kode C dan C++.

Contoh kode integrasi tersedia di GitHub.

Build untuk native

Gunakan langkah-langkah berikut untuk membuat Play Asset Delivery ke dalam Android App Bundle project Anda. Anda tidak perlu menggunakan Android Studio untuk melakukan langkah-langkah ini.

  1. Update versi plugin Android Gradle di file build.gradle project Anda ke 4.0.0 atau yang lebih baru.

  2. Di direktori level teratas project Anda, buat direktori untuk paket aset. Nama direktori ini digunakan sebagai nama paket aset. Nama paket aset harus diawali dengan huruf dan hanya boleh berisi huruf, angka, dan garis bawah.

  3. Dalam direktori paket aset, buat file build.gradle dan tambahkan kode berikut. Pastikan untuk menentukan nama paket aset dan satu jenis pengiriman saja:

    // 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. Pada file build.gradle aplikasi di project, tambahkan nama setiap paket aset dalam project Anda seperti yang ditunjukkan di bawah ini:

    // In the app build.gradle file:
    android {
        ...
        assetPacks = [":asset-pack-name", ":asset-pack2-name"]
    }
    
  5. Dalam file settings.gradle project, sertakan semua paket aset dalam project Anda seperti yang ditunjukkan di bawah ini:

    // In the settings.gradle file:
    include ':app'
    include ':asset-pack-name'
    include ':asset-pack2-name'
    
  6. Dalam direktori paket aset, buat subdirektori berikut: src/main/assets.

  7. Tempatkan aset di direktori src/main/assets. Anda juga dapat membuat subdirektori di sini. Struktur direktori untuk aplikasi Anda sekarang akan terlihat seperti berikut:

    • build.gradle
    • settings.gradle
    • app/
    • asset-pack-name/build.gradle
    • asset-pack-name/src/main/assets/your-asset-directories
  8. Buat Android App Bundle menggunakan Gradle. Dalam app bundle yang dihasilkan, direktori level root kini menyertakan hal berikut:

    • asset-pack-name/manifest/AndroidManifest.xml: Mengonfigurasi mode pengiriman dan ID paket aset
    • asset-pack-name/assets/your-asset-directories: Direktori yang berisi semua aset yang dikirim sebagai bagian dari paket aset

    Gradle menghasilkan manifes untuk setiap paket aset dan menghasilkan direktori assets/ untuk Anda.

  9. (Opsional) Konfigurasikan app bundle Anda untuk mendukung berbagai format kompresi tekstur.

Melakukan integrasi dengan Library Play Asset Delivery

Anda harus menerapkan API ini sesuai dengan jenis pengiriman paket aset yang ingin Anda akses. Langkah-langkah ini ditampilkan dalam diagram alir berikut.

Diagram alir paket aset untuk kode native

Gambar 1. Diagram alur untuk mengakses paket aset

Play Core Native SDK menyediakan file header C play/asset_pack.h untuk meminta paket aset, mengelola download, dan mengakses aset.

Menyiapkan lingkungan pengembangan untuk Play Core Native SDK

Download Play Core Native SDK

Sebelum mendownload, Anda harus menyetujui persyaratan dan ketentuan berikut.

Persyaratan dan Ketentuan

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. Lakukan salah satu hal berikut:

    • Instal Android Studio versi 4.0 atau yang lebih tinggi. Gunakan UI SDK Manager untuk menginstal Android SDK Platform versi 10.0 (level API 29).
    • Instal alat command line Android SDK dan gunakan sdkmanager untuk menginstal Android SDK Platform versi 10.0 (level API 29).
  2. Siapkan Android Studio untuk pengembangan native dengan menggunakan SDK Manager untuk menginstal CMake dan Android Native Development Kit (NDK) terbaru. Untuk informasi selengkapnya tentang membuat atau mengimpor project native, lihat Mulai Menggunakan NDK.

  3. Download file zip dan ekstrak bersama project Anda.

    Link Download Ukuran SHA-256 Checksum
    36 MiB 782a8522d937848c83a715c9a258b95a3ff2879a7cd71855d137b41c00786a5e
  4. Update file build.gradle aplikasi Anda seperti yang ditunjukkan di bawah ini:

    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. Update file CMakeLists.txt aplikasi Anda seperti yang ditunjukkan di bawah ini:

    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
            ...)
    

Pengumpulan Data

Play Core Native SDK dapat mengumpulkan data terkait versi untuk memungkinkan Google meningkatkan produk, termasuk:

  • Nama paket aplikasi
  • Versi paket aplikasi
  • Versi Play Core Native SDK

Data ini akan dikumpulkan saat Anda mengupload paket aplikasi ke Konsol Play. Untuk memilih tidak ikut dalam proses pengumpulan data ini, hapus impor $playcoreDir/playcore-native-metadata.jar di file build.gradle.

Perhatikan bahwa pengumpulan data ini yang terkait dengan penggunaan Play Core Native SDK dan penggunaan data yang dikumpulkan oleh Google terpisah dan tidak bergantung pada pengumpulan dependensi library Google yang dideklarasikan di Gradle saat Anda mengupload paket aplikasi ke Konsol Play.

Pengiriman saat penginstalan

Paket aset yang dikonfigurasi sebagai install-time akan segera tersedia saat aplikasi diluncurkan. Gunakan NDK AAssetManager API untuk mengakses aset yang disalurkan dalam mode ini:

#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);

Pengiriman fast-follow dan on-demand

Bagian berikut menunjukkan cara melakukan inisialisasi API, cara mendapatkan informasi tentang paket aset sebelum mendownloadnya, cara memanggil API untuk memulai download, dan cara mengakses paket yang didownload. Bagian ini berlaku untuk paket aset fast-follow dan on-demand.

Peluncuran aplikasi

Selalu panggil AssetPackManager_init() untuk melakukan inisialisasi API paket aset sebelum memanggil fungsi lainnya. Periksa ada tidaknya kode error paket aset.

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

Pastikan juga untuk memanggil fungsi berikut di onPause() dan onResume() pada ANativeActivityCallbacks:

Mendapatkan informasi download tentang paket aset

Aplikasi wajib mengungkapkan ukuran download sebelum mengambil paket aset. Gunakan fungsi AssetPackManager_requestInfo() guna memulai permintaan asinkron untuk ukuran download dan untuk memeriksa apakah paket sudah mulai didownload. Kemudian gunakan AssetPackManager_getDownloadState() untuk memilih status download (misalnya, memanggil fungsi ini satu kali per frame dalam game loop Anda). Jika permintaan gagal, periksa kode error paket aset.

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

Fungsi AssetPackManager_getDownloadState() akan menampilkan AssetPackDownloadState tipe buram sebagai pointer output. Gunakan pointer ini untuk memanggil fungsi berikut:

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);

Menginstal

Gunakan AssetPackManager_requestDownload() untuk mulai mendownload paket aset pertama kalinya atau untuk meminta update paket aset diselesaikan:

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

Fungsi AssetPackManager_getDownloadState() akan menampilkan AssetPackDownloadState tipe buram. Untuk informasi mengenai cara menggunakan jenis ini, lihat Mendapatkan informasi download.

Hasil download berukuran besar

Jika hasil download lebih besar dari 200 MB dan pengguna tidak menggunakan Wi-Fi, download tidak akan dimulai sebelum pengguna memberikan izin secara eksplisit untuk melanjutkan download dengan menggunakan koneksi data seluler. Demikian pula, jika hasil download berukuran besar dan koneksi Wi-Fi pengguna terputus, download akan dijeda dan perlu izin eksplisit untuk melanjutkan proses download melalui koneksi data seluler. Paket yang dijeda akan berstatus WAITING_FOR_WIFI. Untuk memicu alur UI yang meminta pengguna memberikan persetujuan, gunakan cara berikut:

Konfirmasi pengguna yang diperlukan

Jika paket memiliki status REQUIRES_USER_CONFIRMATION, download tidak akan dilanjutkan sampai pengguna menerima dialog yang ditampilkan dengan AssetPackManager_showConfirmationDialog(). Status ini dapat muncul jika aplikasi tidak dikenali oleh Play. Perlu diperhatikan bahwa dalam hal ini, memanggil AssetPackManager_showConfirmationDialog() akan menyebabkan aplikasi diupdate. Setelah pembaruan, minta aset lagi.

Mengakses paket aset

Anda dapat mengakses paket aset dengan menggunakan panggilan sistem file setelah permintaan download mencapai status COMPLETED. Setiap paket aset disimpan di direktori terpisah dalam penyimpanan internal aplikasi. Gunakan AssetPackManager_getAssetPackLocation() guna mendapatkan AssetPackLocation untuk paket aset yang ditentukan. Gunakan AssetPackLocation_getStorageMethod() di lokasi tersebut untuk menentukan metode penyimpanannya:

  • ASSET_PACK_STORAGE_APK: Paket aset diinstal sebagai APK. Lihat Pengiriman waktu penginstalan untuk mengakses aset ini.
  • ASSET_PACK_STORAGE_FILES: Gunakan AssetPackLocation_getAssetsPath() untuk memperoleh jalur file ke direktori yang berisi aset, atau null jika aset belum didownload. Jangan ubah file yang didownload dalam jalur file ini.
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);
}

Setelah Anda menemukan aset, gunakan fungsi seperti fopen atau ifstream untuk mengakses file tersebut.

Metode Play Core API lainnya

Berikut ini adalah beberapa metode API tambahan yang mungkin ingin Anda gunakan pada aplikasi.

Membatalkan permintaan

Gunakan AssetPackManager_cancelDownload() untuk membatalkan permintaan paket aset aktif. Perhatikan bahwa permintaan ini adalah operasi dengan upaya terbaik.

Meminta penghapusan

Gunakan AssetPackManager_requestRemoval() untuk menjadwalkan penghapusan paket aset.

Langkah berikutnya

Uji Play Asset Delivery secara lokal dan dari Google Play.