Apps Kit SDK logoApps Kit SDK
Tài liệu · AppsKitSDK (AKS) — Hướng dẫn tích hợp Android

5. Khởi tạo SDK và AdsManager

5.1 Lớp Application

Kế thừa AppsKitSDKApplication và triển khai năm thành viên trừu tượng của lớp này:

kotlin
class YourApplication : AppsKitSDKApplication() {

    // Encrypted default-config JSON to fall back on before Remote Config is fetched.
    // Provided to you from the AKS portal for your app.
    override fun setAKSDefaultConfigs(): String = "<encrypted-config-json-from-aks-portal>"

    override fun isTestMode(): Boolean = BuildConfig.DEBUG

    override fun isDevMode(): Boolean = BuildConfig.DEBUG

    override fun setPlatform(): Platform = Platform.GOOGLE // or Platform.AMAZON

    override fun onConfigsReadyToUse(remoteConfig: FirebaseRemoteConfig) {
        // Called once Firebase Remote Config has been fetched/activated.
        // Optional hook if you need to read custom remote-config keys yourself.
    }
}

onCreate() trong lớp cơ sở đã xử lý các tác vụ chính cho bạn — gọi AppsKitSDK.initialize/setPlatform/setTestMode/setDevMode, lấy và lưu cấu hình mặc định, khởi chạy manageRemoteConfigs(), rồi gọi AppsKitSDK.initMMP() để tích hợp AppsFlyer/Adjust/Solar Engine. Bạn không cần tự gọi các phương thức này.

5.2 Khởi tạo mà không kế thừa AppsKitSDKApplication

Không bắt buộc phải kế thừa AppsKitSDKApplication — đây chỉ là lớp bao giúp đơn giản hóa việc tích hợp. Nếu ứng dụng đã có lớp cơ sở Application riêng và không thể thay thế, bạn có thể gọi trực tiếp các phương thức AppsKitSDK mà lớp này sử dụng nội bộ từ Application.onCreate() của mình:

kotlin
class YourApplication : Application() {

    override fun onCreate() {
        super.onCreate()
        FirebaseApp.initializeApp(this)

        AppsKitSDK.initialize(PlatformContext(this), this)
        AppsKitSDK.setPlatform(Platform.GOOGLE) // or Platform.AMAZON
        AppsKitSDK.setTestMode(BuildConfig.DEBUG)
        AppsKitSDK.setDevMode(BuildConfig.DEBUG)
        AppsKitSDK.setTimeToFetchRemoteConfigInSeconds(3600) // optional, defaults to 3600

        AppsKitSDK.saveDefaultConfigJson("<encrypted-config-json-from-aks-portal>")
        AppsKitSDK.manageRemoteConfigs(object : OnRemoteConfigAvailable {
            override fun onRemoteConfigReadyToFetch(remoteConfig: FirebaseRemoteConfig) {
                // optional — your own hook into the fetched remote config
            }
        })

        AppsKitSDK.initMMP() // wires up AppsFlyer / Adjust / Solar Engine from remote-config keys

        // AppsKitSDKApplication does this for you via ActivityLifecycleCallbacks. Without it,
        // AppsKitSDK has no "current activity" — native-ad preloading and any code that calls
        // AppsKitSDK.getCurrentActivity() won't have a target to work with.
        registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityResumed(activity: Activity) {
                AppsKitSDK.setCurrentActivity(PlatformActivity(activity))
                Adjust.onResume() // keeps Adjust session tracking accurate
            }
            override fun onActivityPaused(activity: Activity) {
                Adjust.onPause()
            }
            override fun onActivityCreated(activity: Activity, bundle: Bundle?) {}
            override fun onActivityStarted(activity: Activity) {}
            override fun onActivityStopped(activity: Activity) {}
            override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) {}
            override fun onActivityDestroyed(activity: Activity) {}
        })
    }
}

Khi không kế thừa lớp cơ sở, bạn sẽ không có sẵn cơ chế xử lý broadcast/hộp thoại về kết nối internet và luồng "quảng cáo App Open ở cấp ứng dụng" tích hợp sẵn (requestSplashAppOpenAd/showAppOpenAd, được kích hoạt tự động từ onStart) — đây là các phương thức của đối tượng AppsKitSDKApplication, không được cung cấp trên đối tượng AppsKitSDK. Nếu vẫn muốn hiển thị quảng cáo App Open khi khởi động nguội (cold start), hãy tự gọi AdsManager.loadAppOpen/AdsManager.showAppOpen (xem §6) tại thời điểm phù hợp trong luồng khởi động của bạn.

5.3 Activity

Kế thừa AppsKitSDKBaseActivity (cho màn hình dựa trên AppCompatActivity) hoặc AppsKitSDKBaseComponentActivity (cho màn hình dùng ComponentActivity thuần hoặc chỉ dùng Compose):

kotlin
class HomeActivity : AppsKitSDKBaseActivity() {

    override fun setScreenNameAndId(): Pair<Int, String> = Pair(1, "Home")

    override fun enableAppAutoUpdate(): Boolean = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState) // required — this drives ad-network init, preloading,
                                            // session/day tracking, and the auto SCREEN event
        setContent { /* your Compose UI */ }
    }
}

Kế thừa các lớp cơ sở này giúp bạn tự động có: khởi tạo mạng quảng cáo và tải trước quảng cáo ở màn hình đầu tiên, chuyển tiếp sự kiện vòng đời cho IronSource trong onResume/onPause, theo dõi phiên/số ngày, hộp thoại kết nối internet, lời nhắc cập nhật trong ứng dụng tùy chọn và sendAKSEvent(...) để gửi sự kiện gắn với màn hình này (xem §7). (Việc chuyển tiếp onResume/onPause cho Adjust được thực hiện ở cấp Application — xem §5.2 — chứ không phải tại đây.)

Hộp thoại kết nối internet

Cả hai lớp Activity cơ sở đều theo dõi kết nối trong onResume() và theo mặc định sẽ hiển thị hộp thoại "không có kết nối internet" chặn thao tác mỗi khi mất kết nối, sau đó tự động đóng khi có kết nối trở lại. Tính năng này được bật cho mọi màn hình, trừ khi bạn tắt đi:

kotlin
class HomeActivity : AppsKitSDKBaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        showInternetConnectivity(false) // opt this screen out of the automatic dialog
    }

    // Called on every connectivity change, dialog or not — hook your own UI here
    override fun onInternetConnectivityChange(isInternetAvailable: Boolean?) {
        // e.g. show/hide your own offline banner
    }

    // Optional — return an anchor view to get a "back online" Snackbar when the
    // dialog dismisses on reconnect. Returns null (no Snackbar) by default.
    override fun getSnackBarView(): View? = findViewById(R.id.rootLayout)
}

Khi bạn gọi showInternetConnectivity(false), AKS vẫn gọi onInternetConnectivityChange, nhưng luôn truyền true bất kể trạng thái kết nối thực tế — AKS không theo dõi kết nối thực tế sau khi bạn tắt cơ chế quản lý này. Nếu cần trạng thái chính xác ở đây, hãy tự kiểm tra kết nối để điều khiển giao diện ngoại tuyến của bạn.

Giới hạn màn hình ở hướng dọc

Để khóa màn hình ở hướng dọc, hãy gọi restrictPortraitOnly() (có phạm vi truy cập protected, có sẵn trên cả hai lớp Activity cơ sở):

kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    restrictPortraitOnly()
}

Phương thức này gọi setRequestedOrientation(SCREEN_ORIENTATION_PORTRAIT) thay bạn — ngoại trừ trên Android 8.0 (API 26), nơi lệnh gọi được chủ động bỏ qua vì setRequestedOrientation có thể gây crash trên các Activity dùng theme bán trong suốt hoặc dạng nổi ở riêng phiên bản hệ điều hành này.

5.4 Sự đồng ý của người dùng và khởi tạo quảng cáo

Sau khi thu thập sự đồng ý của người dùng (ví dụ: qua luồng UMP/CMP của Google), hãy thông báo cho AKS để SDK biết quảng cáo được phép hiển thị:

kotlin
AdsManager.initializeAds(userHasGivenConsent = true, isCCPAConsent = true)

5.5 Kiểm soát quảng cáo theo trạng thái xóa quảng cáo / IAP

Nếu ứng dụng bán gói "xóa quảng cáo", hãy tích hợp trạng thái này qua AKS thay vì tự kiểm soát từng lệnh gọi quảng cáo — mọi lệnh gọi tải/hiển thị đều đã kiểm tra cờ này trong nội bộ:

kotlin
AppsKitSDK.setRemoveAdsStatus(true)   // call after a successful purchase/restore
AppsKitSDK.getRemoveAdsStatus()       // check current status