You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android与Web App共享Kotlin代码的配置方法咨询

Hey there! Let me walk you through setting up a Kotlin Multiplatform project that shares code between Android and Web using Android Studio and Gradle—this is exactly what I’ve helped fellow devs nail down many times.

1. Start a New Kotlin Multiplatform Project

Fire up Android Studio and click "New Project". Look for the Kotlin Multiplatform template (it might be under the "Other" category depending on your AS version). When prompted, select Android + JavaScript as your target platforms, then fill in your project name, package ID, and save location. Hit "Finish"—Android Studio will auto-generate the basic project structure for you.

2. Break Down the Auto-Generated Structure

The project will have three core modules, each with a clear purpose:

  • shared: This is your code-sharing hub. It’s split into three source sets:
    • commonMain: Write platform-agnostic Kotlin code here—think data classes, business logic, utility functions that don’t rely on Android or Web APIs.
    • androidMain: Android-specific code that complements the shared logic (e.g., accessing Android system APIs).
    • jsMain: Web/JavaScript-specific code (e.g., interacting with browser APIs).
  • androidApp: A standard Android application module that depends on the shared module—this is where you’ll build your Android UI and integrate shared code.
  • jsApp: A Web application module that compiles to JavaScript, also dependent on shared—this handles Web UI and shared code integration.
3. Write Shared & Platform-Specific Code

Let’s start with simple shared logic first. In shared/src/commonMain/kotlin/[your-package]/, create a file like SharedLogic.kt:

data class User(val id: String, val displayName: String)

fun getGreeting(user: User): String {
    return "Hi there, ${user.displayName}!"
}

This code will work seamlessly on both Android and Web.

For platform-specific functionality, use Kotlin’s expect/actual pattern. For example, if you need to get the current platform name:

  1. In commonMain, declare an expect function:
expect fun getPlatformName(): String
  1. In androidMain, implement the actual version:
actual fun getPlatformName(): String {
    return "Android"
}
  1. In jsMain, implement the Web-specific actual version:
actual fun getPlatformName(): String {
    return "Web (JavaScript)"
}

Now you can call getPlatformName() from commonMain code, and it’ll resolve to the correct platform implementation at runtime.

4. Build & Run Your Apps
  • Android App: Select the androidApp run configuration from the dropdown in Android Studio, then click the run button. You can call shared functions directly in your Android Activities/Fragments—for example, getGreeting(User("1", "Alice")) will return the expected string.
  • Web App: Open the Gradle panel (usually on the right side of Android Studio), navigate to jsApp > Tasks > application > jsRun. Click this task, and it’ll start a local development server. Once it’s running, open the provided URL in your browser to see the Web app using shared code.
5. Key Gradle Configuration Details

Let’s demystify the core Gradle files you’ll interact with:

  • Root settings.gradle.kts: This lists all modules in the project. You’ll see lines like:
    include(":shared", ":androidApp", ":jsApp")
    
  • shared/build.gradle.kts: This is the heart of your multi-platform setup. It defines the target platforms (Android and JS), source sets, and dependencies. For example:
    kotlin {
        androidTarget {
            compilations.all {
                kotlinOptions {
                    jvmTarget = "1.8"
                }
            }
        }
        js(IR) {
            browser()
            binaries.executable()
        }
    
        sourceSets {
            val commonMain by getting
            val androidMain by getting
            val jsMain by getting
        }
    }
    
    android {
        namespace = "com.example.yourpackage"
        compileSdk = 34
        defaultConfig {
            minSdk = 21
        }
    }
    
  • androidApp/build.gradle.kts: This is a standard Android module config, with a dependency on the shared module:
    dependencies {
        implementation(project(":shared"))
        // Other Android dependencies like androidx.core:core-ktx
    }
    
  • jsApp/build.gradle.kts: Configures the JS compilation, including browser support and executable output:
    dependencies {
        implementation(project(":shared"))
    }
    
6. Pro Tips to Smooth Things Out
  • Write unit tests in shared/src/commonTest—this way you test your core logic once, and it runs on both Android and JS platforms.
  • For Web optimization, customize the Webpack config in jsApp/webpack.config.d/ (e.g., add minification, asset handling).
  • When adding third-party libraries, prioritize Kotlin Multiplatform-compatible ones (like Ktor for networking, or SQLDelight for database access) to keep code sharing consistent.

内容的提问来源于stack exchange,提问作者MvG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:22:21