Best practices for integrating the UC U4 kernel

更新时间:
复制 MD 格式

This topic describes how to integrate HTTPDNS into applications that use the UC U4 kernel.

The UC U4 kernel is a high-performance mobile WebView solution developed by Alibaba Group. It is deeply optimized based on the Chromium kernel and offers faster page loading speeds and better compatibility than the system WebView. The kernel is widely used in applications such as Taobao and Alipay and has been validated in large-scale commercial use. For more information, see the official UC engine website.

Background

As the mobile internet grows rapidly, WebView plays an increasingly important role in Android applications. For developers who use the UC kernel, Domain Name System (DNS) resolution is a key factor that affects web security and page loading performance, even though the kernel itself provides excellent rendering. Integrating the Alibaba Cloud HTTPDNS software development kit (SDK) resolves many issues caused by Local DNS. For more information, see Benefits.

This document explains how developers who use the UC U4 kernel can integrate the HTTPDNS SDK to optimize DNS security and performance, which improves the WebView page loading experience.

Prerequisites

  • UC kernel version: 5.18.10.0.250813181008 or later

  • Android API Level: 19 or higher

  • Supported architectures: arm64-v8a, armeabi-v7a

Note

The UC kernel is a commercial product. You must obtain a valid licensing key (AuthKey) to use it. To request authorization, contact UC Engine Official Authorization Service.

Integration steps

1. Integrate the UC U4 kernel

This document provides a brief overview for users who have already integrated the UC U4 kernel. If you have not yet integrated the UC kernel, see the official documentation for the complete integration configuration.

Initialize the UC U4 kernel in the Application class:

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        
        // Initialize the UC kernel
        U4Engine.createInitializer()
            .setContext(this)
            .setAuthKey("your_auth_key") // Replace with your licensing key
            .setClient(object : InitializerClient() {
                override fun onSuccess(info: IRunningCoreInfo) {
                    Log.d("UCWebView", "UC kernel initialized successfully")
                }
                
                override fun onFailed(info: IRunningCoreInfo) {
                    Log.e("UCWebView", "UC kernel initialization failed: ${info.failedInfo()}")
                }
            })
            .start()
    }
}

2. Integrate the HTTPDNS SDK

For detailed steps, see Android SDK integration. The following is a brief overview:

2.1 Add the dependency

Add the HTTPDNS SDK dependency to the app/build.gradle file:

dependencies {
    implementation "com.aliyun.ams:alicloud-android-httpdns:${httpdnsVersion}"
}

2.2 Initialize the HTTPDNS service

Initialize HTTPDNS in the Application class:

private fun initHttpDns() {
    val accountId = "your_account_id" // Replace with your Account ID
    val secretKey = "your_secret_key" // Optional. Replace with your Secret Key
    
    val initConfig = InitConfig.Builder()
        .setEnableHttps(true)
        .setEnableCacheIp(true)
        .setEnableExpiredIp(true)
        .build()
    
    HttpDns.init(accountId, initConfig)
}

For more information about HTTPDNS configuration options, see Configuration interfaces.

3. Use DnsService to host the DNS service

Typically, an application has entry classes, such as WebviewActivity or WebviewFragment, to manage WebViews centrally. In these classes, you can enable the DNS hosting service and set a custom domain resolver. The following example shows how to do this:

import alibaba.httpdns_android_demo.databinding.ActivityWebviewBinding
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.sdk.android.httpdns.RequestIpType
import com.uc.webview.export.WebViewClient
import com.uc.webview.export.extension.DnsService
import com.uc.webview.export.extension.GlobalSettings
import com.uc.webview.export.extension.SettingKeys
import java.net.InetAddress

class WebviewActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityWebviewBinding
    private val TAG = "WebviewActivity"
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        binding = ActivityWebviewBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // Enable the DNS hosting service
        GlobalSettings.set(SettingKeys.EnableDnsHostingService, true)
        
        // Set the HTTPDNS domain resolver
        DnsService.setDoaminResolver(object : DnsService.IDomainResolver() {
            override fun resolve(domain: String, extraInfos: Map<String, String>?): Array<String>? {
                return resolveDomainWithHttpDns(domain, extraInfos)
            }
        })
        
        // Configure and load the page
        configureWebview()
        binding.webview.loadUrl("https://xxx.xxx.xxx")
    }
    
    private fun resolveDomainWithHttpDns(
        domain: String, 
        extraInfos: Map<String, String>?
    ): Array<String>? {
        
        if (domain.isBlank()) {
            return null
        }
        
        // Get the HTTPDNS service instance
        val httpDnsService = HttpDns.getService(applicationContext, "your_account_id")
        
        try {
            // Resolve the domain using HTTPDNS. The synchronous non-blocking interface is recommended.
            val result = httpDnsService?.getHttpDnsResultForHostSyncNonBlocking(
                domain, 
                RequestIpType.auto, 
                extraInfos ?: emptyMap(), 
                null
            )
            
            if (result != null) {
                val ipList = mutableListOf<String>()
                
                // Add IPv4 and IPv6 addresses. The U4 kernel uses them in order.
                ipList.addAll(result.ips.filter { it.isNotBlank() })
                ipList.addAll(result.ipv6s.filter { it.isNotBlank() })
                
                if (ipList.isNotEmpty()) {
                    Log.d(TAG, "HTTPDNS resolution successful: $domain -> ${ipList.joinToString(", ")}")
                    return ipList.toTypedArray()
                }
            }
        } catch (e: Exception) {
            Log.w(TAG, "HTTPDNS resolution failed: $domain", e)
        }
        
        // If no result is returned, fall back to Local DNS
        return try {
            val addresses = InetAddress.getAllByName(domain)
            val ipAddresses = addresses.mapNotNull { it.hostAddress }
            Log.d(TAG, "Local DNS resolution: $domain -> ${ipAddresses.joinToString(", ")}")
            ipAddresses.toTypedArray()
        } catch (e: Exception) {
            Log.e(TAG, "Local DNS resolution failed: $domain", e)
            null
        }
    }
    
    private fun configureWebview() {
        binding.webview.settings.apply {
            javaScriptEnabled = true
            domStorageEnabled = true
            loadWithOverviewMode = true
            useWideViewPort = true
        }
    }
}

Summary

The integration process is straightforward. Simply add the HTTPDNS SDK dependency to your existing UC kernel setup and integrate it using the DNS hosting interface that the UC kernel provides. Thoroughly test the performance in various network environments before deploying to a production environment.