Android KMP初探

Android KMP初探

前言:

最近线上听了Kotlin官网举行的KMP会议,感觉听神奇的,于是就把官方demo下载下来尝试了一下,下载插件和所需要的依赖都用了很久,但是发现里面的代码很少,于是尝试自己手写了一下,遇到了不少问题,这里记录一下.

1.定义:

Kotlin Multiplatform 技术可为多种平台创建应用程序并在平台之间高效重用代码,同时保留原生编程的优势。您的应用程序将在 iOS、Android、macOS、Windows、Linux 等平台上运行。

Compose Multiplatform 是 JetBrains 推出的声明式 UI 框架,可让您为 Android、iOS、桌面和 Web 开发共享 UI。将 Compose Multiplatform 集成到 Kotlin Multiplatform 项目中,更快交付应用和功能,而无需维护多个 UI 实现。

在这里插入图片描述

2.适合各类项目:

在这里插入图片描述

3.优点

使用 Compose Multiplatform 只需构建一次 UI

Compose Multiplatform 是一个基于 Kotlin 和 Jetpack Compose 的声明式框架,用于在 Android、iOS、Web 和桌面(通过 JVM)之间共享 UI。

加速 UI 开发

轻松同步多个 UI 实现,让应用更快交付到用户手中。

组件级重用

使用可在所有目标平台上使用的可自定义微件构建您的 UI。使用预设主题快速开始,或自行创建细节可精确至像素的视觉风格。

根据需要使用原生组件

轻松使用原生 UI 微件或将共享 UI 嵌入现有原生应用。

4.需要几个硬性条件:

在使用 KMP + Compose 进行开发时,需要以下条件,由于没有mac设备就暂时不跑ios项目,跑Android项目也是一样的,不用过于纠结.

  • Mac电脑(苹果开发必须mac)
  • Android Studio
  • Xcode
  • 配置 ios 开发环境(cocoapods、开发者账号等)

5.项目结构:

################## 目录结构说明 ##################
```
.
├── README.md
├── app - 主应用
│   ├── build.gradle.kts
│   ├── MainActivity
│   ├── libs
│   └── src
├── commonMain -公共组件
│   ├── app
│   ├── Greeting
│   ├── Platform
├── appleMain - ios平台
│   ├── getPlatform
├── iosMain - ios业务代码
│   ├── MainViewController
│   └── IOSPlatform
├── gradle
│   └── wrapper
├── gradle.properties
├── gradlew
├── gradlew.bat
├── build.gradle.kts
├── local.properties
└── settings.gradle.kts
################## 目录结构说明 ##################

6.App目录下的build.gradle.kts配置:

import org.jetbrains.compose.desktop.application.dsl.TargetFormat
import org.jetbrains.kotlin.gradle.idea.tcs.extras.isCommonizedKey
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins {alias(libs.plugins.kotlinMultiplatform)alias(libs.plugins.androidApplication)alias(libs.plugins.composeMultiplatform)alias(libs.plugins.composeCompiler)
}
kotlin {androidTarget {@OptIn(ExperimentalKotlinGradlePluginApi::class)compilerOptions {jvmTarget.set(JvmTarget.JVM_11)}}listOf(iosX64(),iosArm64(),iosSimulatorArm64()).forEach { iosTarget ->iosTarget.binaries.framework {baseName = "ComposeApp"isStatic = true}}sourceSets {androidMain.dependencies {implementation(compose.preview)implementation(libs.androidx.activity.compose)}commonMain.dependencies {implementation(compose.runtime)implementation(compose.foundation)implementation(compose.material)implementation(compose.ui)implementation(compose.components.resources)implementation(compose.components.uiToolingPreview)implementation(libs.androidx.lifecycle.viewmodel)implementation(libs.androidx.lifecycle.runtime.compose)implementation(libs.androidx.constraintlayout)}}
}android {namespace = "com.cloud.androidkmpdemo"compileSdk = libs.versions.android.compileSdk.get().toInt()defaultConfig {applicationId = "com.cloud.androidkmpdemo"minSdk = libs.versions.android.minSdk.get().toInt()targetSdk = libs.versions.android.targetSdk.get().toInt()versionCode = 1versionName = "1.0"}packaging {resources {excludes += "/META-INF/{AL2.0,LGPL2.1}"}}buildTypes {getByName("release") {isMinifyEnabled = false}}compileOptions {sourceCompatibility = JavaVersion.VERSION_11targetCompatibility = JavaVersion.VERSION_11}compose.desktop {application {mainClass = "com.example.composeApp.MainKt"nativeDistributions {targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb)packageName = "com.cloud.kmpdemo"packageVersion = "1.0.0"// 描述应用程序description = "A simple demo for KMP"// 版权信息copyright = "© 2024 My Name. All rights reserved."// 厂商信息vendor = "Example vendor"// 设置许可证文件licenseFile.set(project.file("LICENSE.txt"))}}}
}
dependencies {debugImplementation(compose.uiTooling)
}

7.项目的build.gradle.kts配置:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {alias(libs.plugins.androidApplication) apply falsealias(libs.plugins.androidLibrary) apply falsealias(libs.plugins.composeMultiplatform) apply falsealias(libs.plugins.composeCompiler) apply falsealias(libs.plugins.kotlinMultiplatform) apply falsealias(libs.plugins.jetbrainsKotlinAndroid) apply false
}

8.统一的依赖配置:

[versions]
agp = "8.5.2"
android-compileSdk = "34"
android-minSdk = "24"
android-targetSdk = "34"
androidx-activityCompose = "1.9.3"
androidx-appcompat = "1.7.0"
androidx-constraintlayout = "2.2.0"
androidx-core-ktx = "1.15.0"
androidx-espresso-core = "3.6.1"
androidx-lifecycle = "2.8.4"
androidx-material = "1.12.0"
androidx-test-junit = "1.2.1"
compose-multiplatform = "1.7.0"
junit = "4.13.2"
kotlin = "2.1.0"
kotlinVersion = "1.9.0"[libraries]
kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }
kotlin-test-junit = { module = "org.jetbrains.kotlin:kotlin-test-junit", version.ref = "kotlin" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "androidx-core-ktx" }
androidx-test-junit = { group = "androidx.test.ext", name = "junit", version.ref = "androidx-test-junit" }
androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "androidx-espresso-core" }
androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "androidx-appcompat" }
androidx-material = { group = "com.google.android.material", name = "material", version.ref = "androidx-material" }
androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "androidx-constraintlayout" }
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activityCompose" }
androidx-lifecycle-viewmodel = { group = "org.jetbrains.androidx.lifecycle", name = "lifecycle-viewmodel", version.ref = "androidx-lifecycle" }
androidx-lifecycle-runtime-compose = { group = "org.jetbrains.androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "androidx-lifecycle" }[plugins]
androidApplication = { id = "com.android.application", version.ref = "agp" }
androidLibrary = { id = "com.android.library", version.ref = "agp" }
composeMultiplatform = { id = "org.jetbrains.compose", version.ref = "compose-multiplatform" }
composeCompiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
jetbrainsKotlinAndroid = { id = "org.jetbrains.kotlin.android", version.ref = "kotlinVersion" }

9.公共组件:

9.1 Platform接口:

interface Platform {val name: String
}expect fun getPlatform(): Platform

9.2 Greeting类:

class Greeting {private val platform = getPlatform()fun greet(): String {return "Hello, ${platform.name}!"}
}

9.3 App类:

package com.cloud.kmpdemoimport androidkmpdemo.app.generated.resources.Res
import androidkmpdemo.app.generated.resources.compose_multiplatform
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.AlertDialog
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.ui.tooling.preview.Preview@Composable
@Preview
fun App() {MaterialTheme {var showContent by remember { mutableStateOf(false) }var showDialog by remember { mutableStateOf(false) }Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {Button(onClick = { showContent = !showContent }) {Text("Click me")}Button(onClick = { showDialog = !showDialog }) {Text("show Dialog")}AnimatedVisibility(showContent) {val greeting = remember { Greeting().greet() }Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {Image(painterResource(Res.drawable.compose_multiplatform), null)Text("Compose: $greeting")}}AnimatedVisibility(showDialog) {Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {AlertDialogSample()}}}}
}@Composable
@Preview
fun AlertDialogSample(){val dialog = remember { mutableStateOf(true) }if(dialog.value){AlertDialog(onDismissRequest = { dialog.value = false},title = { Text(text = "开启位置服务")},text = { Text(text = "这将意味着,我们会给您提供精准的位置服务,并且您将接受关于您订阅的位置信息。") },confirmButton = {TextButton(onClick = { dialog.value = false}){Text(text = "同意")}},dismissButton = {TextButton(onClick = {dialog.value = false}){Text(text = "取消")}})}
}

10.Android代码:

本文我在原来的基础上加入了一个弹框示例AlertDialogSample()

package com.cloud.kmpdemoimport android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Previewclass MainActivity : ComponentActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContent(){App()}}
}@Preview
@Composable
fun AppAndroidPreview() {App()
}@Preview
@Composable
fun DialogAndroidPreview() {//显示dialogAlertDialogSample()
}
package com.cloud.kmpdemoimport android.os.Build/*** 获取平台版本信息*/
class AndroidPlatform : Platform {override val name: String = "Android ${Build.VERSION.SDK_INT}"
}actual fun getPlatform(): Platform = AndroidPlatform()

11.ios平台代码:

package org.example.kmpdemoimport androidx.compose.ui.window.ComposeUIViewController
import com.cloud.kmpdemo.Appfun MainViewController() = ComposeUIViewController { App() }
package org.example.kmpdemoimport com.cloud.kmpdemo.Platform
import platform.UIKit.UIDeviceclass IOSPlatform: Platform {override val name: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
}actual fun getPlatform(): Platform = IOSPlatform()

12.ios业务代码:

import UIKit
import SwiftUI
import ComposeAppstruct ComposeView: UIViewControllerRepresentable {func makeUIViewController(context: Context) -> UIViewController {MainViewControllerKt.MainViewController()}func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}struct ContentView: View {var body: some View {ComposeView().ignoresSafeArea(.keyboard) // Compose has own keyboard handler}
}
import SwiftUI@main
struct iOSApp: App {var body: some Scene {WindowGroup {ContentView()}}
}

info.plist:

和Android的build.gradle配置文件一样,都是管理依赖和第三方库的.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict><key>CFBundleDevelopmentRegion</key><string>$(DEVELOPMENT_LANGUAGE)</string><key>CFBundleExecutable</key><string>$(EXECUTABLE_NAME)</string><key>CFBundleIdentifier</key><string>$(PRODUCT_BUNDLE_IDENTIFIER)</string><key>CFBundleInfoDictionaryVersion</key><string>6.0</string><key>CFBundleName</key><string>$(PRODUCT_NAME)</string><key>CFBundlePackageType</key><string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string><key>CFBundleShortVersionString</key><string>1.0</string><key>CFBundleVersion</key><string>1</string><key>LSRequiresIPhoneOS</key><true/><key>CADisableMinimumFrameDurationOnPhone</key><true/><key>UIApplicationSceneManifest</key><dict><key>UIApplicationSupportsMultipleScenes</key><false/></dict><key>UILaunchScreen</key><dict/><key>UIRequiredDeviceCapabilities</key><array><string>armv7</string></array><key>UISupportedInterfaceOrientations</key><array><string>UIInterfaceOrientationPortrait</string><string>UIInterfaceOrientationLandscapeLeft</string><string>UIInterfaceOrientationLandscapeRight</string></array><key>UISupportedInterfaceOrientations~ipad</key><array><string>UIInterfaceOrientationPortrait</string><string>UIInterfaceOrientationPortraitUpsideDown</string><string>UIInterfaceOrientationLandscapeLeft</string><string>UIInterfaceOrientationLandscapeRight</string></array>
</dict>
</plist>

13.运行效果如下:

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

14.总结:

以上就是今天的内容,KMP初探,根据不同平台的设备显示不同类型和版本号,代码非常少,再也没有创建xml的烦恼,MainActivity也不需要加载activity_main布局,简直不要太爽,当然KMP如果不熟悉的话跑起来很费劲,我是从0到1自己全部重新撸了一遍,包含Android和IOS两个平台,build插件配置等等,这里我没有Mac环境就不演示iOS的效果了.如果只是单纯写代码看效果没有太大的意义,需要搞清楚整个运行过程和实现原理,在后面进行学习和开发过程中就会事半功倍。

15.项目源码地址:

https://gitee.com/jackning_admin/android-kmpdemo

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/23739.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

鸿蒙NEXT应用App测试-通用测试

注意&#xff1a;大家记得学完通用测试记得再学鸿蒙专项测试 https://blog.csdn.net/weixin_51166786/article/details/145768653 注意&#xff1a;博主有个鸿蒙专栏&#xff0c;里面从上到下有关于鸿蒙next的教学文档&#xff0c;大家感兴趣可以学习下 如果大家觉得博主文章…

GO 快速升级Go版本

由于底层依赖升级了&#xff0c;那我们也要跟着升&#xff0c;go老版本已经不足满足需求了&#xff0c;必须要将版本升级到1.22.0以上 查看当前Go版本 命令查看go版本 go version [rootlocalhost local]# go version go version go1.21.4 linux/amd64 [rootlocalhost local]# …

Redis——用户签到BitMap,UV统计

目录 BitMap 使用场景 1. 用户签到系统 2. 用户行为标记 3. 布隆过滤器&#xff08;Bloom Filter&#xff09; BitMap介绍 Redis中的使用 Redis功能示例 添加&#xff1a; 获取&#xff1a; 批量获取&#xff1a; java中实现 统计本月连续签到次数 UV统计 UV 统计…

Redis|持久化

文章目录 总体介绍RDB&#xff08;Redis DataBase&#xff09;官网介绍案例演示优势劣势 总体介绍 官网地址&#xff1a;https://redis.io/docs/manual/persistence/ 持久化双雄&#xff1a; RDB&#xff08;Redis DataBase&#xff09;&#xff1a;RDB 是 Redis 默认的持久化…

51单片机编程学习笔记——点亮LED

大纲 器件51单片机开发板总结 安装驱动点亮LED烧录 随着最近机器人爆火&#xff0c;之前写的ROS2系列博客《Robot Operating System》也获得了更多的关注。我决定在机器人领域里再走一步&#xff0c;于是想到可以学习单片机。研究了下学习路径&#xff0c;最后还是选择先从51单…

基于Spring Boot的公司资产网站设计与实现(LW+源码+讲解)

专注于大学生项目实战开发,讲解,毕业答疑辅导&#xff0c;欢迎高校老师/同行前辈交流合作✌。 技术范围&#xff1a;SpringBoot、Vue、SSM、HLMT、小程序、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、安卓app、大数据、物联网、机器学习等设计与开发。 主要内容&#xff1a;…

华为2025年技术发布会:智能汽车核心技术大爆发

近日&#xff0c;华为在鸿蒙智行尊界技术发布会上发布了多项智能汽车核心技术&#xff0c;涵盖智能驾驶、安全防护、通信系统、座舱交互及电池技术等领域&#xff0c;标志着其从“被动智能”向“自主智能”的战略升级。 以下是核心技术的综合梳理&#xff1a; 六大核心创新 途…

ctfshow做题笔记—栈溢出—pwn57~pwn60

目录 前言 一、pwn57&#xff08;先了解一下简单的64位shellcode吧&#xff09; 二、pwn58 三、pwn59&#xff08;64位 无限制&#xff09; 四、pwn60&#xff08;入门难度shellcode&#xff09; 前言 往前写了几道题&#xff0c;与shellcode有关&#xff0c;关于shellc…

测试面试题:以一个登录窗口为例,设计一下登录界面测试的思路和方法

在测试登录窗口时,可以从 表单测试、 逻辑判断和 业务流程三个方面设计测试思路和方法。以下是一个详细的测试方案: 1. 表单测试 表单测试主要关注输入框、按钮等UI元素的正确性和用户体验。 测试点: 输入框测试 用户名和密码输入框是否正常显示。输入框是否支持预期的字符类…

小型字符级语言模型的改进方向和策略

小型字符级语言模型的改进方向和策略 一、回顾小型字符级语言模型的处理流程 前文我们已经从零开始构建了一个小型字符级语言模型,那么如何改进和完善我们的模型呢?有哪些改进的方向?我们先回顾一下模型的流程: 图1 小型字符级语言模型的处理流程 (1)核心模块交互过程:…

基于数据可视化+SpringBoot+安卓端的数字化施工项目计划与管理平台设计和实现

博主介绍&#xff1a;硕士研究生&#xff0c;专注于信息化技术领域开发与管理&#xff0c;会使用java、标准c/c等开发语言&#xff0c;以及毕业项目实战✌ 从事基于java BS架构、CS架构、c/c 编程工作近16年&#xff0c;拥有近12年的管理工作经验&#xff0c;拥有较丰富的技术架…

初识.git文件泄露

.git 文件泄露 当在一个空目录执行 git init 时&#xff0c;Git 会创建一个 .git 目录。 这个目录包含所有的 Git 存储和操作的对象。 如果想备份或复制一个版本库&#xff0c;只需把这个目录拷贝至另一处就可以了 这是一种常见的安全漏洞&#xff0c;指的是网站的 .git 目录…

基于Nanopi duo2的WiFi智能摄像头

1.固件包烧录 https://wiki.friendlyelec.com/wiki/index.php/NanoPi_Duo2/zh#.E8.BF.9E.E6.8E.A5WiFi 固件包链接以及烧录工具都在上面链接中 烧录过程 使用读卡器将SD卡插入到电脑,然后打开烧录工具 2.通过串口工具连接板子使其连接WiFi 对应的串口工具,就是这个HyperT…

单片机延时函数怎么写规范?

我们以前在开发产品的时候&#xff0c;肯定会碰到一些延时需求&#xff0c;比如常见的LED闪烁&#xff0c;按键消抖&#xff0c;控制IO口输出时序等等。 别小看延时&#xff0c;这个小问题&#xff0c;想做好&#xff0c;甚至要考虑到程序架构层面。 在开发板上&#xff0c;可能…

Dify私有化部署自己的AI Agent

1、下载Dify git clone gitgithub.com:langgenius/dify.git 2、创建Dify配置 进入dify目录下的docker目录中,复制.env.example为 .env 3、使用Docker命令进行部署Dify docker compose up -d 4、访问Dify http://localhost/install 5、 设置模型供应商 配置环境变量&#xff1…

【Unity】鱼群效果模拟

鱼群效果模拟 文章目录 鱼群效果模拟Boid算法实现方式version1_CPUversion2_GPUversion3_Multilaterationversion4_Bitonic_Sorting &#xff08;GPU友好&#xff09;version5_Skinning &#xff08;TODO&#xff09; 细节项优化项参考链接 Boid算法 Boid算法是一种模拟群体行…

【AI时代】可视化训练模型工具LLaMA-Factory安装与使用

文章目录 安装训练使用 安装 官方地址&#xff1a;https://github.com/hiyouga/LLaMA-Factory 创建虚拟环境 conda create -n llama-factory conda activate llama-factory安装 git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git cd LLaMA-Factory pip in…

tailwindcss学习03

01 入门 02 vue中接入 03 工具类优先 准备 vue.svg <svg viewBox"0 0 40 40" xmlns"http://www.w3.org/2000/svg"> <defs> <linearGradient x1"50%" y1"0%" x2"50%" y2"100%" id"a"&…

Java 笔记(自用)

Java是一种面向对象(opp)的、解释性的跨平台语言。所谓的跨平台是Java的一个编译好的.class文件可以在多个系统下运行。解释性则是编译后的代码需要解释器来执行&#xff0c;与之相对应的c/c是编译性语言&#xff0c;编译后的代码可以直接被机器执行。 jdkjrejava的开发工具 …

Matlab——图像保存导出成好看的.pdf格式文件

点击图像的右上角&#xff0c;点击第一个保存按钮键。