content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package top.chengdongqing.weui.core.utils import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.BatteryManager import android.widget.Toast import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.statusBars import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp @Composable fun rememberStatusBarHeight(): Dp { val density = LocalDensity.current val statusBars = WindowInsets.statusBars return remember { with(density) { statusBars.getTop(this).toDp() } } } @Composable fun rememberBatteryInfo(): BatteryInfo { val batteryStatus = LocalContext.current.registerReceiver( null, IntentFilter(Intent.ACTION_BATTERY_CHANGED) ) val level by remember { derivedStateOf { val level = batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, 0) ?: 0 val scale = batteryStatus?.getIntExtra(BatteryManager.EXTRA_SCALE, 0) ?: 0 (level / scale.toFloat() * 100).toInt() } } val isCharging by remember { derivedStateOf { val status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1 status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL } } return BatteryInfo(level, isCharging) } data class BatteryInfo( val level: Int, val isCharging: Boolean ) fun Context.showToast(text: String) { Toast.makeText(this, text, Toast.LENGTH_SHORT).show() }
WeUI/core/utils/src/main/kotlin/top/chengdongqing/weui/core/utils/SystemUtils.kt
1851119124
package top.chengdongqing.weui.core.utils import android.app.Activity import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat @Composable fun SetupStatusBarStyle(isDark: Boolean = true) { val view = LocalView.current val window = (view.context as Activity).window val insetsController = remember { WindowCompat.getInsetsController(window, view) } val initialStyle = remember { insetsController.isAppearanceLightStatusBars } DisposableEffect(isDark) { insetsController.isAppearanceLightStatusBars = isDark onDispose { insetsController.isAppearanceLightStatusBars = initialStyle } } } @Composable fun SetupFullscreen(isFullscreen: Boolean = true) { val view = LocalView.current val window = (view.context as Activity).window val insetsController = remember { WindowCompat.getInsetsController(window, view) } DisposableEffect(Unit) { if (isFullscreen) { // 让状态栏区域可用于布局 WindowCompat.setDecorFitsSystemWindows(window, false) // 隐藏系统状态栏、导航栏等 insetsController.hide(WindowInsetsCompat.Type.systemBars()) // 当手动将状态栏或导航栏滑出后只短暂显示一会儿就收起 insetsController.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } else { insetsController.show(WindowInsetsCompat.Type.systemBars()) } onDispose { insetsController.show(WindowInsetsCompat.Type.systemBars()) } } }
WeUI/core/utils/src/main/kotlin/top/chengdongqing/weui/core/utils/ThemeUtils.kt
3449708331
package top.chengdongqing.weui.core.utils import android.content.ContentValues import android.content.Context import android.graphics.Bitmap import android.media.MediaMetadataRetriever import android.net.Uri import android.os.Build import android.os.Environment import android.provider.MediaStore import android.util.Size import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import top.chengdongqing.weui.core.data.model.MediaItem import top.chengdongqing.weui.core.data.model.MediaType import top.chengdongqing.weui.core.data.model.isImage import top.chengdongqing.weui.core.data.model.isVideo import top.chengdongqing.weui.core.ui.theme.R import java.io.IOException object MediaStoreUtils { fun createContentValues( filename: String, mediaType: MediaType, mimeType: String, context: Context ): ContentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, filename) put(MediaStore.MediaColumns.MIME_TYPE, mimeType) val directory = when (mediaType) { MediaType.IMAGE -> Environment.DIRECTORY_PICTURES MediaType.VIDEO -> Environment.DIRECTORY_MOVIES MediaType.AUDIO -> Environment.DIRECTORY_MUSIC MediaType.RECORDING -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { Environment.DIRECTORY_RECORDINGS } else { Environment.DIRECTORY_MUSIC } } val appName = context.getString(R.string.app_name) val relativePath = "$directory/$appName" put(MediaStore.MediaColumns.RELATIVE_PATH, relativePath) put(MediaStore.MediaColumns.IS_PENDING, 1) } fun finishPending(uri: Uri, context: Context) { val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.IS_PENDING, 0) } context.contentResolver.update(uri, contentValues, null, null) } fun getContentUri(mediaType: MediaType): Uri = when (mediaType) { MediaType.IMAGE -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI MediaType.VIDEO -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI MediaType.AUDIO, MediaType.RECORDING -> MediaStore.Audio.Media.EXTERNAL_CONTENT_URI } } suspend fun Context.loadMediaThumbnail(media: MediaItem): Any? { // 图片在低版本系统中加载原图 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && !media.isVideo()) { return media.uri } else { return withContext(Dispatchers.IO) { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // 高版本系统直接加载缩略图 contentResolver.loadThumbnail( media.uri, Size(200, 200), null ) } else { // 低版本系统获取视频首帧 loadVideoThumbnail(media.uri) } } catch (e: IOException) { e.printStackTrace() if (media.isImage()) { media.uri } else { null } } } } } fun Context.loadVideoThumbnail(uri: Uri): Bitmap? { return MediaMetadataRetriever().use { it.setDataSource(this, uri) it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH) ?.toInt() it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT) ?.toInt() it.getFrameAtTime(1, MediaMetadataRetriever.OPTION_CLOSEST_SYNC) } }
WeUI/core/utils/src/main/kotlin/top/chengdongqing/weui/core/utils/MediaUtils.kt
3048503632
package top.chengdongqing.weui.core.utils import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.remember import java.util.concurrent.ExecutorService import java.util.concurrent.Executors @Composable fun rememberSingleThreadExecutor(): ExecutorService { val executor = remember { Executors.newSingleThreadExecutor() } DisposableEffect(Unit) { onDispose { executor.shutdown() } } return executor }
WeUI/core/utils/src/main/kotlin/top/chengdongqing/weui/core/utils/ExecutorUtils.kt
1679874757
package top.chengdongqing.weui.core.utils import kotlin.random.Random fun randomFloat(min: Float, max: Float): Float { require(min < max) { "最小值必须小于最大值" } return Random.nextFloat() * (max - min) + min } fun randomInt(min: Int, max: Int): Int { require(min < max) { "最小值必须小于最大值" } return Random.nextInt(min, max + 1) }
WeUI/core/utils/src/main/kotlin/top/chengdongqing/weui/core/utils/RandomUtils.kt
2031522885
package top.chengdongqing.weui.core.utils import android.content.Context import android.os.Build import android.os.VibrationEffect import android.os.Vibrator import android.os.VibratorManager /** * 触发短震动 */ fun Context.vibrateShort() { vibrate(15) } /** * 触发长震动 */ fun Context.vibrateLong() { vibrate(400) } private fun Context.vibrate(milliseconds: Long) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val vibrator = getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager vibrator.defaultVibrator.vibrate( VibrationEffect.createOneShot( milliseconds, VibrationEffect.DEFAULT_AMPLITUDE ) ) } else { @Suppress("DEPRECATION") val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator @Suppress("DEPRECATION") vibrator.vibrate(milliseconds) } }
WeUI/core/utils/src/main/kotlin/top/chengdongqing/weui/core/utils/VibrateUtils.kt
1730153598
package top.chengdongqing.weui.core.utils import androidx.compose.ui.graphics.Color /** * 生成不重复的随机颜色 * @param count 需要的颜色数量 */ fun generateColors(count: Int): List<Color> { return List(count) { i -> // 在360度色相环上均匀分布颜色 val hue = (360 * i / count) % 360 // 使用HSV色彩空间转换为Color Color.hsv(hue.toFloat(), 0.85f, 0.85f) } }
WeUI/core/utils/src/main/kotlin/top/chengdongqing/weui/core/utils/ColorUtils.kt
360681361
package top.chengdongqing.weui.core.utils import android.content.ClipData import android.content.ClipboardManager import android.content.Context fun Context.getClipboardData(): String? = clipboardManager?.primaryClip?.takeIf { it.itemCount > 0 } ?.getItemAt(0)?.text?.toString() fun Context.setClipboardData(data: String, label: String = "label") { clipboardManager?.apply { val clip = ClipData.newPlainText(label, data) setPrimaryClip(clip) } } private val Context.clipboardManager: ClipboardManager? get() = getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
WeUI/core/utils/src/main/kotlin/top/chengdongqing/weui/core/utils/ClipboardUtils.kt
3858816084
package top.chengdongqing.weui.core.utils import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import kotlin.math.roundToInt fun Modifier.clickableWithoutRipple(enabled: Boolean = true, onClick: () -> Unit) = composed { this.clickable( interactionSource = remember { MutableInteractionSource() }, indication = null, enabled ) { onClick() } } fun Boolean.format(trueLabel: String = "是", falseLabel: String = "否") = if (this) trueLabel else falseLabel fun Boolean?.isTrue(): Boolean = this == true fun Offset.toIntOffset() = IntOffset(x.roundToInt(), y.roundToInt()) fun Size.toIntSize() = IntSize(width.roundToInt(), height.roundToInt())
WeUI/core/utils/src/main/kotlin/top/chengdongqing/weui/core/utils/Extentions.kt
3843575516
package top.chengdongqing.weui.core.utils import android.content.Context import android.content.Intent import android.net.Uri import androidx.core.content.FileProvider import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File fun deleteFile(file: File): Boolean { if (file.isDirectory) { // 如果是目录,递归删除其下的所有文件和子目录 file.listFiles()?.forEach { child -> deleteFile(child) } } // 删除文件或目录本身 return file.delete() } suspend fun calculateFileSize(file: File): Long = withContext(Dispatchers.IO) { if (file.isFile) { // 如果是文件,直接返回其大小 file.length() } else if (file.isDirectory) { // 如果是目录,递归计算所有子文件和子目录的大小 val children = file.listFiles() var totalSize: Long = 0 if (children != null) { for (child in children) { totalSize += calculateFileSize(child) } } totalSize } else { 0 } } fun formatFileSize(file: File): String { val size = if (file.exists()) file.length() else 0 return formatFileSize(size) } fun formatFileSize(size: Long): String { return when { size < 1024 -> "$size B" size < 1024 * 1024 -> "${(size / 1024f).format()} KB" size < 1024 * 1024 * 1024 -> "${(size / (1024 * 1024f)).format()} MB" else -> "${(size / (1024 * 1024 * 1024f)).format()} GB" } } fun Context.getFileProviderUri(file: File): Uri { return FileProvider.getUriForFile(this, "$packageName.provider", file) } fun Context.shareFile(file: File, mimeType: String = "image/*") { val sharingUri = getFileProviderUri(file) val intent = Intent(Intent.ACTION_SEND).apply { this.type = mimeType putExtra(Intent.EXTRA_STREAM, sharingUri) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } startActivity(intent) } fun Context.openFile(file: File, mimeType: String) { val uri = getFileProviderUri(file) val intent = Intent(Intent.ACTION_VIEW).apply { setDataAndType(uri, mimeType) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } startActivity(intent) }
WeUI/core/utils/src/main/kotlin/top/chengdongqing/weui/core/utils/FileUtils.kt
3159702918
package top.chengdongqing.core.data.repository import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("top.chengdongqing.core.data.repository.test", appContext.packageName) } }
WeUI/core/data/repository/src/androidTest/java/top/chengdongqing/core/data/repository/ExampleInstrumentedTest.kt
3071509418
package top.chengdongqing.core.data.repository import org.junit.Assert.* import org.junit.Test /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
WeUI/core/data/repository/src/test/java/top/chengdongqing/core/data/repository/ExampleUnitTest.kt
104687491
package top.chengdongqing.core.data.repository import top.chengdongqing.weui.core.data.model.MediaItem import top.chengdongqing.weui.core.data.model.MediaType interface LocalMediaRepository { suspend fun loadMediaList(types: Array<MediaType>): List<MediaItem> }
WeUI/core/data/repository/src/main/kotlin/top/chengdongqing/core/data/repository/LocalMediaRepository.kt
3080044399
package top.chengdongqing.core.data.repository import android.content.Context import android.provider.MediaStore import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import top.chengdongqing.weui.core.data.model.MediaItem import top.chengdongqing.weui.core.data.model.MediaType class LocalMediaRepositoryImpl(private val context: Context) : LocalMediaRepository { override suspend fun loadMediaList(types: Array<MediaType>): List<MediaItem> { return withContext(Dispatchers.IO) { val mediaItems = mutableListOf<MediaItem>() val selectionUri = MediaStore.Files.getContentUri("external") val projection = arrayOf( MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DISPLAY_NAME, MediaStore.Files.FileColumns.DURATION, MediaStore.Files.FileColumns.DATE_ADDED, MediaStore.Files.FileColumns.MEDIA_TYPE, MediaStore.Files.FileColumns.MIME_TYPE ) val selection = "${MediaStore.Files.FileColumns.MEDIA_TYPE} IN (${types.joinToString(separator = ",") { "?" }})" val selectionArgs = types.map { it.columnType.toString() }.toTypedArray() val sortOrder = "${MediaStore.Files.FileColumns.DATE_ADDED} DESC" context.contentResolver.query( selectionUri, projection, selection, selectionArgs, sortOrder )?.use { cursor -> val idColumn = cursor.getColumnIndex(MediaStore.Files.FileColumns._ID) val nameColumn = cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME) val durationColumn = cursor.getColumnIndex(MediaStore.Files.FileColumns.DURATION) val dateColumn = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATE_ADDED) val mediaTypeColumn = cursor.getColumnIndex(MediaStore.Files.FileColumns.MEDIA_TYPE) val mimeTypeColumn = cursor.getColumnIndex(MediaStore.Files.FileColumns.MIME_TYPE) while (cursor.moveToNext()) { val fileUri = MediaStore.Files.getContentUri("external", cursor.getLong(idColumn)) val mediaType = MediaType.ofColumnType(cursor.getInt(mediaTypeColumn)) mediaItems.add( MediaItem( fileUri, filename = cursor.getString(nameColumn), mediaType = mediaType ?: MediaType.IMAGE, mimeType = cursor.getString(mimeTypeColumn), duration = cursor.getLong(durationColumn), date = cursor.getLong(dateColumn) ) ) } } mediaItems } } }
WeUI/core/data/repository/src/main/kotlin/top/chengdongqing/core/data/repository/LocalMediaRepositoryImpl.kt
872165307
package top.chengdongqing.weui.data.model import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("top.chengdongqing.weui.data.model.test", appContext.packageName) } }
WeUI/core/data/model/src/androidTest/java/top/chengdongqing/weui/data/model/ExampleInstrumentedTest.kt
3668168372
package top.chengdongqing.weui.data.model import org.junit.Assert.* import org.junit.Test /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
WeUI/core/data/model/src/test/java/top/chengdongqing/weui/data/model/ExampleUnitTest.kt
2451745846
package top.chengdongqing.weui.core.data.model import android.provider.MediaStore enum class MediaType(val columnType: Int) { IMAGE(MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE), VIDEO(MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO), AUDIO(MediaStore.Files.FileColumns.MEDIA_TYPE_AUDIO), RECORDING(MediaStore.Files.FileColumns.MEDIA_TYPE_AUDIO); companion object { fun ofColumnType(columnType: Int): MediaType? { return entries.find { it.columnType == columnType } } } } enum class VisualMediaType { IMAGE, VIDEO, IMAGE_AND_VIDEO }
WeUI/core/data/model/src/main/kotlin/top/chengdongqing/weui/core/data/model/MediaType.kt
4030465271
package top.chengdongqing.weui.core.data.model import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onStart sealed interface Result<out T> { data class Success<T>(val data: T) : Result<T> data class Error(val exception: Throwable) : Result<Nothing> data object Loading : Result<Nothing> } fun <T> Flow<T>.asResult(): Flow<Result<T>> = map<T, Result<T>> { Result.Success(it) } .onStart { emit(Result.Loading) } .catch { emit(Result.Error(it)) }
WeUI/core/data/model/src/main/kotlin/top/chengdongqing/weui/core/data/model/Result.kt
1515791903
package top.chengdongqing.weui.core.data.model import android.net.Uri import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class MediaItem( val uri: Uri, val filename: String, val mediaType: MediaType, val mimeType: String, val duration: Long = 0, val date: Long = 0 ) : Parcelable fun MediaItem.isImage(): Boolean = this.mediaType == MediaType.IMAGE fun MediaItem.isVideo(): Boolean = this.mediaType == MediaType.VIDEO
WeUI/core/data/model/src/main/kotlin/top/chengdongqing/weui/core/data/model/MediaItem.kt
4278162882
package top.chengdongqing.weui.core.data.model enum class DragAnchor { Start, Center, End }
WeUI/core/data/model/src/main/kotlin/top/chengdongqing/weui/core/data/model/DragAchor.kt
4266998787
package top.chengdongqing.weui.home import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import top.chengdongqing.weui.R import top.chengdongqing.weui.core.ui.components.divider.WeDivider import top.chengdongqing.weui.core.ui.theme.FontColorDark import top.chengdongqing.weui.core.ui.theme.InvertColorMatrix import top.chengdongqing.weui.core.utils.clickableWithoutRipple import top.chengdongqing.weui.home.data.MenuDataProvider import top.chengdongqing.weui.home.data.model.MenuGroup import top.chengdongqing.weui.home.data.model.MenuItem @Composable fun HomeScreen(onNavigateTo: (route: String) -> Unit) { var current by rememberSaveable { mutableStateOf<Int?>(null) } LazyColumn( verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.background) .statusBarsPadding() .padding(horizontal = 16.dp) ) { item { HomeHeader() } itemsIndexed(MenuDataProvider.menuGroups) { index, item -> MenuGroup( item, expanded = index == current, onNavigateTo ) { current = if (current == index) null else index } } item { Spacer(Modifier.height(60.dp)) HomeFooter() } } } @Composable private fun HomeHeader() { Column(Modifier.padding(40.dp)) { Image( painter = painterResource(id = R.drawable.ic_logo), contentDescription = "WeUI", colorFilter = if (MaterialTheme.homeColorScheme.iconColor != Color.Unspecified) ColorFilter.tint( MaterialTheme.homeColorScheme.iconColor ) else null, modifier = Modifier.height(21.dp) ) Spacer(modifier = Modifier.height(19.dp)) Text( text = "WeUI 是一套同微信原生视觉体验一致的基础样式库,由微信官方设计团队为微信内网页和微信小程序量身设计,令用户的使用感知更加统一。", color = MaterialTheme.homeColorScheme.headerColor, fontSize = 14.sp ) } } @Composable private fun HomeFooter() { Row( horizontalArrangement = Arrangement.Center, modifier = Modifier .fillMaxWidth() .padding(vertical = 40.dp) ) { Image( painter = painterResource(id = R.drawable.ic_footer_link), contentDescription = null, colorFilter = if (MaterialTheme.homeColorScheme.iconColor != Color.Unspecified) { ColorFilter.colorMatrix(InvertColorMatrix) } else { null }, modifier = Modifier.size(84.dp, 19.dp) ) } } @Composable private fun MenuGroup( group: MenuGroup, expanded: Boolean, onNavigateTo: (route: String) -> Unit, onToggleExpand: () -> Unit ) { Column( Modifier .clip(RoundedCornerShape(4.dp)) .background(MaterialTheme.colorScheme.onBackground) ) { MenuGroupHeader(group, expanded) { if (group.path != null) { onNavigateTo(group.path) } else { onToggleExpand() } } if (group.children != null) { AnimatedVisibility(visible = expanded) { Column { val children = remember { group.children.sortedBy { it.label } } children.forEachIndexed { index, item -> MenuGroupItem(item, onNavigateTo) if (index < group.children.lastIndex) { WeDivider(Modifier.padding(horizontal = 20.dp)) } } } } } } } @Composable private fun MenuGroupHeader(group: MenuGroup, expanded: Boolean, onClick: () -> Unit) { Row( Modifier .alpha(if (expanded) 0.5f else 1f) .clickableWithoutRipple { onClick() } .padding(20.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = group.title, color = MaterialTheme.homeColorScheme.fontColor, fontSize = 17.sp, modifier = Modifier.weight(1f) ) Image( painter = painterResource(id = group.iconId), contentDescription = null, colorFilter = if (MaterialTheme.homeColorScheme.iconColor != Color.Unspecified) ColorFilter.tint( MaterialTheme.homeColorScheme.iconColor ) else null, modifier = Modifier.size(30.dp) ) } } @Composable private fun MenuGroupItem(item: MenuItem, onNavigateTo: (route: String) -> Unit) { Row( Modifier .clickable { onNavigateTo(item.route) } .padding(horizontal = 20.dp, vertical = 16.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = item.label, color = MaterialTheme.homeColorScheme.fontColor, fontSize = 17.sp, modifier = Modifier.weight(1f) ) Icon( painter = painterResource(id = R.drawable.ic_arrow_right), contentDescription = null, tint = MaterialTheme.homeColorScheme.arrowColor ) } } private data class HomeColors( val iconColor: Color, val headerColor: Color, val fontColor: Color, val arrowColor: Color ) private val MaterialTheme.homeColorScheme: HomeColors @Composable get() = HomeColors( iconColor = if (isSystemInDarkTheme()) FontColorDark else Color.Unspecified, headerColor = colorScheme.onSecondary, fontColor = colorScheme.onPrimary, arrowColor = colorScheme.onSecondary )
WeUI/app/src/main/kotlin/top/chengdongqing/weui/home/Home.kt
2971482688
package top.chengdongqing.weui.home.data.model import androidx.annotation.DrawableRes internal data class MenuGroup( val title: String, @DrawableRes val iconId: Int, val children: List<MenuItem>? = null, val path: String? = null )
WeUI/app/src/main/kotlin/top/chengdongqing/weui/home/data/model/MenuGroup.kt
2956770220
package top.chengdongqing.weui.home.data.model internal data class MenuItem( val label: String, val route: String )
WeUI/app/src/main/kotlin/top/chengdongqing/weui/home/data/model/MenuItem.kt
4000362849
package top.chengdongqing.weui.home.data import top.chengdongqing.weui.R import top.chengdongqing.weui.home.data.model.MenuGroup import top.chengdongqing.weui.home.data.model.MenuItem internal object MenuDataProvider { val menuGroups = listOf( MenuGroup( "基础组件", R.drawable.ic_nav_layout, listOf( MenuItem("Badge", "badge"), MenuItem("Loading", "loading"), MenuItem("LoadMore", "load_more"), MenuItem("Progress", "progress"), MenuItem("Steps", "steps"), MenuItem("Swiper", "swiper"), MenuItem("RefreshView", "refresh_view"), MenuItem("TabView", "tab_view"), MenuItem("SwipeAction", "swipe_action"), MenuItem("Skeleton", "skeleton"), MenuItem("Tree", "tree") ) ), MenuGroup( "表单组件", R.drawable.ic_nav_form, listOf( MenuItem("Button", "button"), MenuItem("Checkbox", "checkbox"), MenuItem("Radio", "radio"), MenuItem("Switch", "switch"), MenuItem("Slider", "slider"), MenuItem("Picker", "picker"), MenuItem("Input", "input"), MenuItem("Rate", "rate") ) ), MenuGroup( "媒体组件", R.drawable.ic_nav_search, listOf( MenuItem("Camera", "camera"), MenuItem("MediaPicker", "media_picker"), MenuItem("AudioRecorder", "audio_recorder"), MenuItem("AudioPlayer", "audio_player"), MenuItem("LivePlayer", "live_player"), MenuItem("LivePusher", "live_pusher"), MenuItem("Gallery", "gallery"), MenuItem("ImageCropper", "image_cropper"), MenuItem("PanoramicImage", "panoramic_image") ) ), MenuGroup( "操作反馈", R.drawable.ic_nav_feedback, listOf( MenuItem("ActionSheet", "action_sheet"), MenuItem("Dialog", "dialog"), MenuItem("Popup", "popup"), MenuItem("Toast", "toast"), MenuItem("InformationBar", "information_bar"), MenuItem("ContextMenu", "context_menu") ) ), MenuGroup( "系统服务", R.drawable.ic_nav_layout, listOf( MenuItem("Contacts", "contacts"), MenuItem("Clipboard", "clipboard"), MenuItem("CalendarEvents", "calendar_events"), MenuItem("DeviceInfo", "device_info"), MenuItem("Downloader", "downloader"), MenuItem("Database", "database"), MenuItem("SystemStatus", "system_status"), MenuItem("SMS", "sms"), MenuItem("InstalledApps", "installed_apps"), MenuItem("Keyboard", "keyboard"), MenuItem("Notification", "notification") ) ), MenuGroup( "网络服务", R.drawable.ic_nav_search, listOf( MenuItem("HTTPRequest", "http_request"), MenuItem("FileUpload", "file_upload"), MenuItem("FileDownload", "file_download"), MenuItem("WebSocket", "web_socket") ) ), MenuGroup( "硬件接口", R.drawable.ic_nav_nav, listOf( MenuItem("Screen", "screen"), MenuItem("Flashlight", "flashlight"), MenuItem("Vibration", "vibration"), MenuItem("Wi-Fi", "wifi"), MenuItem("Bluetooth", "bluetooth"), MenuItem("NFC", "nfc"), MenuItem("GNSS", "gnss"), MenuItem("Infrared", "infrared"), MenuItem("Gyroscope", "gyroscope"), MenuItem("Compass", "compass"), MenuItem("Accelerometer", "accelerometer"), MenuItem("Hygrothermograph", "hygrothermograph"), MenuItem("Fingerprint", "fingerprint") ) ), MenuGroup( "图表组件", R.drawable.ic_nav_layout, listOf( MenuItem("BarChart", "bar_chart"), MenuItem("LineChart", "line_chart"), MenuItem("PieChart", "pie_chart") ) ), MenuGroup( "二维码", R.drawable.ic_nav_form, listOf( MenuItem("QrCodeScanner", "qrcode_scanner"), MenuItem("QrCodeGenerator", "qrcode_generator") ) ), MenuGroup( "地图组件", R.drawable.ic_nav_feedback, listOf( MenuItem("LocationPreview", "location_preview"), MenuItem("LocationPicker", "location_picker") ) ), MenuGroup( "扩展示例", R.drawable.ic_nav_search, listOf( MenuItem("Calendar", "calendar"), MenuItem("Clock", "clock"), MenuItem("DropCard", "drop_card"), MenuItem("SearchBar", "search_bar"), MenuItem("FileBrowser", "file_browser"), MenuItem("Paint", "paint"), MenuItem("IndexedList", "indexed_list"), MenuItem("DragSorter", "drag_sorter"), MenuItem("DividingRule", "dividing_rule"), MenuItem("OrgTree", "org_tree"), MenuItem("DigitalRoller", "digital_roller"), MenuItem("DigitalKeyboard", "digital_keyboard"), MenuItem("CubicBezier", "cubic_bezier"), MenuItem("NotificationBar", "notification_bar"), MenuItem("VideoChannel", "video_channel"), MenuItem("SolarSystem", "solar_system") ) ), MenuGroup( "层级规范", R.drawable.ic_nav_zindex, path = "layers" ) ) }
WeUI/app/src/main/kotlin/top/chengdongqing/weui/home/data/MenuDataProvider.kt
1384050143
package top.chengdongqing.weui import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import top.chengdongqing.weui.core.ui.theme.WeUITheme import top.chengdongqing.weui.navigation.AppNavHost class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { WeUITheme { AppNavHost() } } } }
WeUI/app/src/main/kotlin/top/chengdongqing/weui/MainActivity.kt
2067794858
package top.chengdongqing.weui.layers import androidx.compose.animation.core.animateDp import androidx.compose.animation.core.updateTransition import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import kotlinx.coroutines.delay import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.clickableWithoutRipple @Composable fun LayersScreen() { WeScreen( title = "WeUI页面层级", description = "用于规范WeUI页面元素所属层级、层级顺序及组合规范。" ) { val width = LocalConfiguration.current.screenWidthDp.dp / 2 var expanded by remember { mutableStateOf(false) } val transition = updateTransition(targetState = expanded, label = "layers_transition") LaunchedEffect(Unit) { delay(500) expanded = true } Box( modifier = Modifier .fillMaxSize() .clickableWithoutRipple { expanded = !expanded } .padding(top = 100.dp), contentAlignment = Alignment.TopCenter ) { Box( modifier = Modifier .zIndex(4f) .width(width) .aspectRatio(3 / 5f) .offset( x = transition.animateDp(label = "") { if (it) (-60).dp else 0.dp }.value, y = transition.animateDp(label = "") { if (it) 60.dp else 0.dp }.value ) .border(1.dp, Color.hsl(0f, 0f, 0.8f, 0.5f)) ) Box( modifier = Modifier .zIndex(3f) .width(width) .aspectRatio(3 / 5f) .offset( x = transition.animateDp(label = "") { if (it) (-20).dp else 0.dp }.value, y = transition.animateDp(label = "") { if (it) 20.dp else 0.dp }.value ) .background(Color(0f, 0f, 0f, 0.5f)) ) Box( modifier = Modifier .zIndex(2f) .width(width) .aspectRatio(3 / 5f) .offset( x = transition.animateDp(label = "") { if (it) 20.dp else 0.dp }.value, y = transition.animateDp(label = "") { if (it) (-20).dp else 0.dp }.value ) .background(Color(40 / 255f, 187 / 255f, 102 / 255f, 0.5f)) ) Box( modifier = Modifier .zIndex(1f) .width(width) .aspectRatio(3 / 5f) .offset( x = transition.animateDp(label = "") { if (it) 60.dp else 0.dp }.value, y = transition.animateDp(label = "") { if (it) (-60).dp else 0.dp }.value ) .background(Color.White) ) } } }
WeUI/app/src/main/kotlin/top/chengdongqing/weui/layers/Layers.kt
3037082705
package top.chengdongqing.weui.navigation import androidx.compose.animation.AnimatedContentTransitionScope import androidx.compose.animation.core.tween import androidx.compose.runtime.Composable import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import top.chengdongqing.weui.feature.basic.navigation.addBasicGraph import top.chengdongqing.weui.feature.charts.navigation.addChartGraph import top.chengdongqing.weui.feature.feedback.navigation.addFeedbackGraph import top.chengdongqing.weui.feature.form.navigation.addFormGraph import top.chengdongqing.weui.feature.hardware.navigation.addHardwareGraph import top.chengdongqing.weui.feature.location.navigation.addLocationGraph import top.chengdongqing.weui.feature.media.navigation.addMediaGraph import top.chengdongqing.weui.feature.network.navigation.addNetworkGraph import top.chengdongqing.weui.feature.qrcode.navigation.addQrCodeGraph import top.chengdongqing.weui.feature.samples.navigation.addSamplesGraph import top.chengdongqing.weui.feature.system.navigation.addSystemGraph import top.chengdongqing.weui.home.HomeScreen import top.chengdongqing.weui.layers.LayersScreen @Composable fun AppNavHost() { val navController = rememberNavController() NavHost( navController, startDestination = "home", enterTransition = { slideIntoContainer( AnimatedContentTransitionScope.SlideDirection.Left, animationSpec = tween(300) ) }, exitTransition = { slideOutOfContainer( AnimatedContentTransitionScope.SlideDirection.Left, animationSpec = tween(300) ) }, popEnterTransition = { slideIntoContainer( AnimatedContentTransitionScope.SlideDirection.Right, animationSpec = tween(300) ) }, popExitTransition = { slideOutOfContainer( AnimatedContentTransitionScope.SlideDirection.Right, animationSpec = tween(300) ) } ) { composable("home") { HomeScreen { navController.navigate(it) } } addBasicGraph() addFormGraph() addFeedbackGraph() addMediaGraph(navController) addSystemGraph(navController) addNetworkGraph() addHardwareGraph() addChartGraph() addQrCodeGraph() addLocationGraph() addSamplesGraph() composable("layers") { LayersScreen() } } } /** * 为什么官方文档不建议直接将 `NavController` 传递给可组合项(Composable)? * * 主要是基于架构和测试的考量。直接在可组合项中操作导航可能导致几个问题: * * 1. 耦合性增加:直接使用 NavController 会让你的可组合项和导航逻辑紧密耦合。这意味着可组合项需要知道导航的具体细节,比如导航路由的名称。这样一来,你的可组合项不仅要负责显示 UI,还要管理导航逻辑,违反了单一职责原则。 * * 2. 测试困难:当可组合项直接依赖 NavController 时,单元测试会更加困难。你需要模拟 NavController 或创建一个环境,其中包含 NavController 的实例。这增加了测试的复杂性,尤其是当导航逻辑变得复杂时。 * * 3. 重组问题:在可组合函数中直接调用 NavController.navigate() 可能会在每次重组时触发导航动作。由于 Compose 会根据状态变化频繁重组,这可能导致意料之外的导航行为或性能问题。 * * 4. 灵活性减少:将导航逻辑紧密绑定到可组合项中,减少了组件的可重用性。如果将来你想要在不同的上下文中重用同一个可组合项,但是导航目标不同,你可能需要重写或调整可组合项以适应新的需求。 * * 5. 遵循最佳实践:Jetpack Compose 提倡使用事件回调(如上例中的 onNavigateToFriends)来处理用户交互和相关的UI逻辑,而将应用逻辑(如导航)留给组件的调用者来处理。这样做不仅使得你的UI组件更加通用和可测试,也使得架构更加清晰,因为它强制进行了逻辑分层。 * * 尽管直接传递 NavController 到组件可能在初期看起来没有问题,但随着应用规模的增长和需求的变化,上述问题可能会逐渐显现,导致代码难以维护和扩展。因此,遵循官方的建议可以使你的代码更加健壮,易于测试和维护。 * * * * NavHost提供了四种主要的动画配置:enterTransition、exitTransition、popEnterTransition和popExitTransition。 * * 1. enterTransition(进入转换):当导航到一个新的组件时,这个新组件的进入动画。简而言之,当你从组件A导航到组件B时,组件B的`enterTransition`定义了它是如何出现在屏幕上的。 * * 2. exitTransition`退出转换):当从当前组件导航到另一个组件时,当前组件的退出动画。当你从组件A导航到组件B时,组件A的`exitTransition`定义了它是如何从屏幕上消失的。 * * 3. popEnterTransition(弹出进入转换):当从当前组件回退到前一个组件时,那个前一个组件的进入动画。如果你在组件B中按下返回按钮,预期回到组件A,那么组件A的`popEnterTransition`定义了它是如何重新出现在屏幕上的。 * * 4. popExitTransition(弹出退出转换):当通过回退操作退出当前组件时,当前组件的退出动画。如果你在组件B中按下返回按钮回到组件A,那么组件B的`popExitTransition`定义了它是如何从屏幕上消失的。 */
WeUI/app/src/main/kotlin/top/chengdongqing/weui/navigation/AppNavHost.kt
4166035704
package top.chengdongqing.weui import com.android.build.api.dsl.CommonExtension import org.gradle.api.JavaVersion import org.gradle.api.Project import org.gradle.kotlin.dsl.dependencies import org.gradle.kotlin.dsl.withType import org.jetbrains.kotlin.gradle.tasks.KotlinCompile internal fun Project.configureAndroidCompose( commonExtension: CommonExtension<*, *, *, *, *, *>, ) { commonExtension.apply { compileSdk = 34 defaultConfig { minSdk = 26 } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } buildFeatures { compose = true } composeOptions { kotlinCompilerExtensionVersion = libs.findVersion("compose-compiler").get().toString() } dependencies { val bom = libs.findLibrary("compose-bom").get() add("implementation", platform(bom)) listOf( "core.ktx", "lifecycle.runtime.ktx", "activity.compose", "ui", "ui.graphics", "ui.tooling.preview", "material3", "material.icons.extended" ).forEach { alias -> add("implementation", libs.findLibrary(alias).get()) } add("testImplementation", libs.findLibrary("junit").get()) add("androidTestImplementation", libs.findLibrary("androidx.test.ext.junit").get()) add("androidTestImplementation", libs.findLibrary("espresso.core").get()) add("androidTestImplementation", platform(bom)) add("androidTestImplementation", libs.findLibrary("ui.test.junit4").get()) add("debugImplementation", libs.findLibrary("ui.tooling").get()) add("debugImplementation", libs.findLibrary("ui.test.manifest").get()) } } tasks.withType<KotlinCompile>().configureEach { kotlinOptions { jvmTarget = JavaVersion.VERSION_17.toString() } } }
WeUI/build-logic/convention/src/main/kotlin/top/chengdongqing/weui/AndroidCompose.kt
2903497417
package top.chengdongqing.weui import org.gradle.api.Project import org.gradle.api.artifacts.VersionCatalog import org.gradle.api.artifacts.VersionCatalogsExtension import org.gradle.kotlin.dsl.getByType val Project.libs get(): VersionCatalog = extensions.getByType<VersionCatalogsExtension>().named("libs")
WeUI/build-logic/convention/src/main/kotlin/top/chengdongqing/weui/ProjectExtensions.kt
4053874742
import androidx.room.gradle.RoomExtension import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.dependencies import top.chengdongqing.weui.libs class AndroidRoomConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("androidx.room") apply("com.google.devtools.ksp") } extensions.configure<RoomExtension> { schemaDirectory("$projectDir/schemas") } dependencies { add("implementation", libs.findLibrary("room.runtime").get()) add("implementation", libs.findLibrary("room.ktx").get()) add("ksp", libs.findLibrary("room.compiler").get()) } } } }
WeUI/build-logic/convention/src/main/kotlin/AndroidRoomConventionPlugin.kt
3336510173
import com.android.build.api.dsl.ApplicationExtension import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.getByType import top.chengdongqing.weui.configureAndroidCompose class AndroidComposeApplicationConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("com.android.application") apply("org.jetbrains.kotlin.android") } val extension = extensions.getByType<ApplicationExtension>() configureAndroidCompose(extension) } } }
WeUI/build-logic/convention/src/main/kotlin/AndroidComposeApplicationConventionPlugin.kt
4164384609
import com.android.build.gradle.LibraryExtension import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.getByType import top.chengdongqing.weui.configureAndroidCompose class AndroidComposeLibraryConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("com.android.library") apply("org.jetbrains.kotlin.android") } val extension = extensions.getByType<LibraryExtension>().apply { defaultConfig { consumerProguardFile("consumer-rules.pro") } } configureAndroidCompose(extension) } } }
WeUI/build-logic/convention/src/main/kotlin/AndroidComposeLibraryConventionPlugin.kt
4116939315
package top.chengdongqing.weui.feature.form import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("top.chengdongqing.weui.feature.form.test", appContext.packageName) } }
WeUI/feature/form/src/androidTest/java/top/chengdongqing/weui/feature/form/ExampleInstrumentedTest.kt
1040898073
package top.chengdongqing.weui.feature.form import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
WeUI/feature/form/src/test/java/top/chengdongqing/weui/feature/form/ExampleUnitTest.kt
976511680
package top.chengdongqing.weui.feature.form.navigation import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import top.chengdongqing.weui.feature.form.screens.ButtonScreen import top.chengdongqing.weui.feature.form.screens.CheckboxScreen import top.chengdongqing.weui.feature.form.screens.InputScreen import top.chengdongqing.weui.feature.form.screens.PickerScreen import top.chengdongqing.weui.feature.form.screens.RadioScreen import top.chengdongqing.weui.feature.form.screens.RateScreen import top.chengdongqing.weui.feature.form.screens.SliderScreen import top.chengdongqing.weui.feature.form.screens.SwitchScreen fun NavGraphBuilder.addFormGraph() { composable("button") { ButtonScreen() } composable("checkbox") { CheckboxScreen() } composable("radio") { RadioScreen() } composable("switch") { SwitchScreen() } composable("slider") { SliderScreen() } composable("picker") { PickerScreen() } composable("input") { InputScreen() } composable("Rate") { RateScreen() } }
WeUI/feature/form/src/main/kotlin/top/chengdongqing/weui/feature/form/navigation/FormGraph.kt
3634482922
package top.chengdongqing.weui.feature.form.screens import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.input.WeInput import top.chengdongqing.weui.core.ui.components.input.WeTextarea import top.chengdongqing.weui.core.ui.components.screen.WeScreen @Composable fun InputScreen() { WeScreen(title = "Input", description = "输入框") { val value = remember { mutableStateMapOf<String, String>() } WeInput( value = value["account"], label = "账号", placeholder = "请输入" ) { value["account"] = it } WeInput( value = value["password"], label = "密码", placeholder = "请输入", keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password) ) { value["password"] = it } WeInput("WeUI", label = "微信号", disabled = true) WeTextarea(value["desc"] ?: "", placeholder = "请描述你所经历的事情", max = 200) { value["desc"] = it } Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "确定") } }
WeUI/feature/form/src/main/kotlin/top/chengdongqing/weui/feature/form/screens/Input.kt
3419057180
package top.chengdongqing.weui.feature.form.screens import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import top.chengdongqing.weui.core.ui.components.radio.RadioOption import top.chengdongqing.weui.core.ui.components.radio.WeRadioGroup import top.chengdongqing.weui.core.ui.components.screen.WeScreen @Composable fun RadioScreen() { WeScreen(title = "Radio", description = "单选框") { var value by remember { mutableStateOf("2") } WeRadioGroup( listOf( RadioOption(label = "cell standard", value = "1"), RadioOption(label = "cell standard", value = "2"), RadioOption(label = "cell standard", value = "3", disabled = true), ), value = value ) { value = it } } }
WeUI/feature/form/src/main/kotlin/top/chengdongqing/weui/feature/form/screens/Radio.kt
4039714890
package top.chengdongqing.weui.feature.form.screens import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.components.slider.WeSlider import top.chengdongqing.weui.core.utils.format @Composable fun SliderScreen() { WeScreen(title = "Slider", description = "滑块") { Column( modifier = Modifier.padding(horizontal = 12.dp), horizontalAlignment = Alignment.CenterHorizontally ) { var value by remember { mutableFloatStateOf(0f) } WeSlider( value, formatter = { "${it.format(0)}%" } ) { value = it } Spacer(modifier = Modifier.height(20.dp)) var value1 by remember { mutableFloatStateOf(0f) } KvRow(key = "定义可选值区间", value = value1.format()) WeSlider( value = value1, range = -999.99f..999.99f ) { value1 = it } Spacer(modifier = Modifier.height(20.dp)) var value2 by remember { mutableFloatStateOf(0f) } var value2String by remember { mutableStateOf("0") } KvRow(key = "滑动结束后触发", value = value2String) WeSlider( value = value2, range = 0f..1f, onChangeFinished = { value2String = value2.format() } ) { value2 = it } } } } @Composable fun KvRow(key: String, value: String) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth() ) { Text( text = key, color = MaterialTheme.colorScheme.onPrimary, fontSize = 14.sp ) Text( text = value, color = MaterialTheme.colorScheme.onPrimary, fontSize = 14.sp ) } }
WeUI/feature/form/src/main/kotlin/top/chengdongqing/weui/feature/form/screens/Slider.kt
216175741
package top.chengdongqing.weui.feature.form.screens import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.ui.components.button.ButtonSize import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.screen.WeScreen @Composable fun ButtonScreen() { WeScreen( title = "Button", description = "按钮", padding = PaddingValues(bottom = 100.dp), verticalArrangement = Arrangement.spacedBy(16.dp) ) { WeButton(text = "主要操作") WeButton(text = "主要操作", loading = true) WeButton(text = "次要操作", type = ButtonType.PLAIN) WeButton(text = "次要操作", type = ButtonType.PLAIN, loading = true) WeButton(text = "警示操作", type = ButtonType.DANGER) WeButton(text = "警示操作", type = ButtonType.DANGER, loading = true) Spacer(Modifier) WeButton(text = "按钮禁用", disabled = true) Spacer(Modifier) WeButton(text = "medium 按钮", size = ButtonSize.MEDIUM) WeButton(text = "medium 按钮", size = ButtonSize.MEDIUM, type = ButtonType.PLAIN) WeButton(text = "medium 按钮", size = ButtonSize.MEDIUM, type = ButtonType.DANGER) Spacer(Modifier) Row { WeButton(text = "按钮", size = ButtonSize.SMALL) Spacer(Modifier.width(12.dp)) WeButton(text = "按钮", size = ButtonSize.SMALL, type = ButtonType.PLAIN) Spacer(Modifier.width(12.dp)) WeButton(text = "按钮", size = ButtonSize.SMALL, type = ButtonType.DANGER) } } }
WeUI/feature/form/src/main/kotlin/top/chengdongqing/weui/feature/form/screens/Button.kt
3562836919
package top.chengdongqing.weui.feature.form.screens import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import top.chengdongqing.weui.core.ui.components.checkbox.CheckboxOption import top.chengdongqing.weui.core.ui.components.checkbox.WeCheckboxGroup import top.chengdongqing.weui.core.ui.components.screen.WeScreen @Composable fun CheckboxScreen() { WeScreen(title = "Checkbox", description = "复选框") { var values by remember { mutableStateOf<List<Int>>(emptyList()) } WeCheckboxGroup( listOf( CheckboxOption(label = "standard is dealt for u.", value = 1), CheckboxOption(label = "standard is dealicient for u.", value = 2), CheckboxOption(label = "standard is dealicient for u.", value = 3, disabled = true) ), values ) { values = it } } }
WeUI/feature/form/src/main/kotlin/top/chengdongqing/weui/feature/form/screens/Checkbox.kt
578476726
package top.chengdongqing.weui.feature.form.screens import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.input.WeInput import top.chengdongqing.weui.core.ui.components.picker.DateType import top.chengdongqing.weui.core.ui.components.picker.TimeType import top.chengdongqing.weui.core.ui.components.picker.WePicker import top.chengdongqing.weui.core.ui.components.picker.rememberDatePickerState import top.chengdongqing.weui.core.ui.components.picker.rememberSingleColumnPickerState import top.chengdongqing.weui.core.ui.components.picker.rememberTimePickerState import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.ChineseDateFormatter import top.chengdongqing.weui.core.utils.DefaultTimeFormatter import java.time.LocalDate import java.time.LocalTime import java.time.format.DateTimeFormatter @Composable fun PickerScreen() { WeScreen( title = "Picker", description = "滚动选择器" ) { DatePickDemo() Spacer(modifier = Modifier.height(40.dp)) TimePickDemo() Spacer(modifier = Modifier.height(40.dp)) CountryPickDemo() Spacer(modifier = Modifier.height(40.dp)) CarPickDemo() Spacer(modifier = Modifier.height(60.dp)) } } @Composable private fun DatePickDemo() { val state = rememberDatePickerState() var value by remember { mutableStateOf(LocalDate.now()) } WeInput( value = value.format(DateTimeFormatter.ofPattern(ChineseDateFormatter)), textAlign = TextAlign.Center, disabled = true ) Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "选择年月日") { state.show(value) { value = it } } Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "选择年月", type = ButtonType.PLAIN) { state.show(value, type = DateType.MONTH) { value = it } } Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "选择年", type = ButtonType.PLAIN) { state.show(value, type = DateType.YEAR) { value = it } } } @Composable private fun TimePickDemo() { val picker = rememberTimePickerState() var value by remember { mutableStateOf(LocalTime.now()) } WeInput( value = value.format(DateTimeFormatter.ofPattern(DefaultTimeFormatter)), textAlign = TextAlign.Center, disabled = true ) Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "选择时分秒") { picker.show(value) { value = it } } Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "选择时分", type = ButtonType.PLAIN) { picker.show(value, type = TimeType.MINUTE) { value = it } } Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "选择时", type = ButtonType.PLAIN) { picker.show(value, type = TimeType.HOUR) { value = it } } } @Composable private fun CountryPickDemo() { val picker = rememberSingleColumnPickerState() var value by remember { mutableIntStateOf(0) } val range = remember { listOf( "中国", "美国", "德国", "法国", "英国", "瑞士", "希腊", "西班牙", "荷兰" ) } WeInput( value = range[value], textAlign = TextAlign.Center, disabled = true ) Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "选择国家") { picker.show( title = "选择国家", range, value ) { value = it } } } @Composable private fun CarPickDemo() { var visible by remember { mutableStateOf(false) } var values by remember { mutableStateOf(arrayOf(0, 0)) } val sourceMap = remember { arrayOf( "小米" to listOf("SU7"), "小鹏" to listOf("G9", "G6", "P7i"), "理想" to listOf("Mega", "L9", "L8", "L7") ) } var tmpValues by remember { mutableStateOf(values) } val ranges by remember { derivedStateOf { arrayOf( sourceMap.map { it.first }, sourceMap[tmpValues.first()].second ) } } WePicker( visible, ranges, values, title = "选择汽车", onCancel = { visible = false }, onColumnValueChange = { _, _, newValues -> tmpValues = newValues } ) { values = it } WeInput( value = remember(values) { arrayOf( ranges[0].getOrElse(values[0]) { 0 }, ranges[1].getOrElse(values[1]) { 0 } ).joinToString(" ") }, textAlign = TextAlign.Center, disabled = true ) Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "选择汽车") { visible = true } }
WeUI/feature/form/src/main/kotlin/top/chengdongqing/weui/feature/form/screens/Picker.kt
2350082174
package top.chengdongqing.weui.feature.form.screens import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.components.switch.WeSwitch @Composable fun SwitchScreen() { WeScreen(title = "Switch", description = "开关") { val checked = remember { mutableStateOf(false) } WeSwitch(checked = checked.value) { checked.value = it } Spacer(Modifier.height(16.dp)) WeSwitch(checked = checked.value, disabled = true) { checked.value = it } } }
WeUI/feature/form/src/main/kotlin/top/chengdongqing/weui/feature/form/screens/Switch.kt
148392980
package top.chengdongqing.weui.feature.form.screens import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import top.chengdongqing.weui.core.ui.components.rate.WeRate import top.chengdongqing.weui.core.ui.components.screen.WeScreen @Composable fun RateScreen() { WeScreen( title = "Rate", description = "评分", verticalArrangement = Arrangement.spacedBy(20.dp) ) { var value by remember { mutableFloatStateOf(4f) } DemoItem("基本用法") { WeRate(value) { value = it } } DemoItem("设置数量") { WeRate(value, count = 8) { value = it } } DemoItem("支持半星") { WeRate(value, allowHalf = true) { value = it } } DemoItem("不可修改") { WeRate(value) } } } @Composable private fun DemoItem(label: String, content: @Composable () -> Unit) { Row( modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.onBackground, RoundedCornerShape(4.dp)) .padding(vertical = 18.dp, horizontal = 16.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = label, color = MaterialTheme.colorScheme.onPrimary, fontSize = 15.sp, fontWeight = FontWeight.Bold ) content() } }
WeUI/feature/form/src/main/kotlin/top/chengdongqing/weui/feature/form/screens/Rate.kt
3458732029
package top.chengdongqing.weui.feature.hardware import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("top.chengdongqing.weui.feature.hardware.test", appContext.packageName) } }
WeUI/feature/hardware/src/androidTest/java/top/chengdongqing/weui/feature/hardware/ExampleInstrumentedTest.kt
1183930731
package top.chengdongqing.weui.feature.hardware import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
WeUI/feature/hardware/src/test/java/top/chengdongqing/weui/feature/hardware/ExampleUnitTest.kt
2726426090
package top.chengdongqing.weui.feature.hardware.navigation import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import top.chengdongqing.weui.feature.hardware.screens.AccelerometerScreen import top.chengdongqing.weui.feature.hardware.screens.BluetoothScreen import top.chengdongqing.weui.feature.hardware.screens.CompassScreen import top.chengdongqing.weui.feature.hardware.screens.FingerprintScreen import top.chengdongqing.weui.feature.hardware.screens.FlashlightScreen import top.chengdongqing.weui.feature.hardware.screens.GNSSScreen import top.chengdongqing.weui.feature.hardware.screens.GyroscopeScreen import top.chengdongqing.weui.feature.hardware.screens.HygrothermographScreen import top.chengdongqing.weui.feature.hardware.screens.InfraredScreen import top.chengdongqing.weui.feature.hardware.screens.NFCScreen import top.chengdongqing.weui.feature.hardware.screens.ScreenScreen import top.chengdongqing.weui.feature.hardware.screens.VibrationScreen import top.chengdongqing.weui.feature.hardware.screens.WiFiScreen fun NavGraphBuilder.addHardwareGraph() { composable("screen") { ScreenScreen() } composable("flashlight") { FlashlightScreen() } composable("vibration") { VibrationScreen() } composable("wifi") { WiFiScreen() } composable("bluetooth") { BluetoothScreen() } composable("nfc") { NFCScreen() } composable("gnss") { GNSSScreen() } composable("infrared") { InfraredScreen() } composable("gyroscope") { GyroscopeScreen() } composable("compass") { CompassScreen() } composable("accelerometer") { AccelerometerScreen() } composable("hygrothermograph") { HygrothermographScreen() } composable("fingerprint") { FingerprintScreen() } }
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/navigation/HardwareGraph.kt
299233505
package top.chengdongqing.weui.feature.hardware.utils import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext @Composable fun rememberSensorValue(type: Int, observing: Boolean): Float? { return rememberSensorValues(type, observing)?.first() } @Composable fun rememberSensorValues(type: Int, observing: Boolean): Array<Float>? { val (values, setValues) = remember { mutableStateOf<Array<Float>?>(null) } val context = LocalContext.current val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager val sensor = sensorManager.getDefaultSensor(type) if (sensor != null) { val eventListener = remember { object : SensorEventListener { override fun onSensorChanged(event: SensorEvent?) { event?.let { setValues(it.values.toTypedArray()) } } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {} } } LaunchedEffect(observing) { if (observing) { sensorManager.registerListener( eventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL ) } else { sensorManager.unregisterListener(eventListener) } } DisposableEffect(Unit) { onDispose { sensorManager.unregisterListener(eventListener) } } } return values } fun determineAccuracy(accuracy: Int): String? { return when (accuracy) { SensorManager.SENSOR_STATUS_ACCURACY_HIGH -> "高精度" SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM -> "中精度" SensorManager.SENSOR_STATUS_ACCURACY_LOW -> "低精度" else -> null } }
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/utils/SensorUtils.kt
607224443
package top.chengdongqing.weui.feature.hardware.screens import android.hardware.Sensor import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem import top.chengdongqing.weui.core.ui.components.cardlist.cartList import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.format import top.chengdongqing.weui.feature.hardware.utils.rememberSensorValue @Composable fun HygrothermographScreen() { WeScreen(title = "Hygrothermograph", description = "温湿度计", scrollEnabled = false) { val (observing, setObserving) = remember { mutableStateOf(false) } val temperature = rememberSensorValue(Sensor.TYPE_AMBIENT_TEMPERATURE, observing) val humidity = rememberSensorValue(Sensor.TYPE_RELATIVE_HUMIDITY, observing) if (!observing) { WeButton(text = "开始监听") { setObserving(true) } } else { WeButton(text = "取消监听", type = ButtonType.PLAIN) { setObserving(false) } } Spacer(modifier = Modifier.height(40.dp)) LazyColumn(modifier = Modifier.cartList()) { item { WeCardListItem( label = "温度", value = temperature?.let { "${temperature.format()}°C" } ?: "未知" ) WeCardListItem( label = "湿度", value = humidity?.let { "${humidity.format()}%" } ?: "未知") } } } }
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/Hygrothermograph.kt
4013020083
package top.chengdongqing.weui.feature.hardware.screens import android.Manifest import android.annotation.SuppressLint import android.app.Activity import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Build import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.rememberMultiplePermissionsState import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.cardlist.cartList import top.chengdongqing.weui.core.ui.components.divider.WeDivider import top.chengdongqing.weui.core.ui.components.loading.LoadMoreType import top.chengdongqing.weui.core.ui.components.loading.WeLoadMore import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.showToast @SuppressLint("MissingPermission") @OptIn(ExperimentalPermissionsApi::class) @Composable fun BluetoothScreen() { WeScreen(title = "Bluetooth", description = "蓝牙", scrollEnabled = false) { val context = LocalContext.current val permissionState = rememberMultiplePermissionsState( remember { mutableListOf( Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION ).apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { add(Manifest.permission.BLUETOOTH_CONNECT) add(Manifest.permission.BLUETOOTH_SCAN) } } } ) val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager val bluetoothAdapter = bluetoothManager?.adapter val launchBluetooth = rememberBluetoothLauncher() val bluetoothList = rememberBluetoothDevices() WeButton(text = "扫描蓝牙") { if (permissionState.allPermissionsGranted) { if (bluetoothAdapter == null) { context.showToast("此设备不支持蓝牙") } else if (!bluetoothAdapter.isEnabled) { launchBluetooth() } else { bluetoothList.clear() bluetoothAdapter.startDiscovery() } } else { permissionState.launchMultiplePermissionRequest() } } Spacer(modifier = Modifier.height(40.dp)) BluetoothList(bluetoothList) } } @Composable private fun BluetoothList(bluetoothList: List<BluetoothInfo>) { if (bluetoothList.isNotEmpty()) { LazyColumn(modifier = Modifier.cartList()) { itemsIndexed(bluetoothList, key = { _, item -> item.address }) { index, device -> BluetoothListItem(device) if (index < bluetoothList.lastIndex) { WeDivider() } } } } else { WeLoadMore(type = LoadMoreType.ALL_LOADED) } } @Composable private fun BluetoothListItem(bluetooth: BluetoothInfo) { Column(modifier = Modifier.padding(vertical = 16.dp)) { Text( text = bluetooth.name, color = MaterialTheme.colorScheme.onPrimary, fontSize = 17.sp ) Spacer(modifier = Modifier.height(4.dp)) Text( text = buildString { appendLine("信号强度:${bluetooth.rssi}") appendLine("MAC地址:${bluetooth.address}") appendLine("蓝牙类型:${bluetooth.type}") append("绑定状态:${bluetooth.bondState}") }, color = MaterialTheme.colorScheme.onSecondary, fontSize = 10.sp, lineHeight = 14.sp ) } } @Composable private fun rememberBluetoothDevices(): MutableList<BluetoothInfo> { val context = LocalContext.current val bluetoothList = remember { mutableStateListOf<BluetoothInfo>() } DisposableEffect(Unit) { val filter = IntentFilter(BluetoothDevice.ACTION_FOUND) val receiver = BluetoothBroadcastReceiver { val index = bluetoothList.indexOfFirst { item -> item.address == it.address } if (index == -1) { bluetoothList.add(it) } else { bluetoothList[index] = it } } context.registerReceiver(receiver, filter) onDispose { context.unregisterReceiver(receiver) } } return bluetoothList } @Composable private fun rememberBluetoothLauncher(): () -> Unit { val context = LocalContext.current val bluetoothLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.StartActivityForResult() ) { if (it.resultCode == Activity.RESULT_OK) { context.showToast("蓝牙已打开") } } return { val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) bluetoothLauncher.launch(intent) } } private class BluetoothBroadcastReceiver(val onFound: (info: BluetoothInfo) -> Unit) : BroadcastReceiver() { @SuppressLint("MissingPermission") override fun onReceive(context: Context, intent: Intent) { when (intent.action) { BluetoothDevice.ACTION_FOUND -> { val device = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent.getParcelableExtra( BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java ) } else { @Suppress("DEPRECATION") intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) } if (device?.name?.isNotEmpty() == true) { val rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE) onFound(buildBluetoothInfo(device, rssi.toInt())) } } } } } @SuppressLint("MissingPermission") private fun buildBluetoothInfo(device: BluetoothDevice, rssi: Int): BluetoothInfo { return BluetoothInfo( name = device.name, address = device.address, rssi = "${rssi}dBm (${calculateSinglePercentage(rssi)}%)", type = determineBluetoothType(device.type), bondState = determineBluetoothBondState(device.bondState), uuids = device.uuids?.map { it.toString() }?.distinct() ?: listOf() ) } private fun calculateSinglePercentage(rssi: Int): Int { return ((rssi + 100) * 100) / 100 } private fun determineBluetoothType(type: Int): String { return when (type) { BluetoothDevice.DEVICE_TYPE_CLASSIC -> "经典蓝牙" BluetoothDevice.DEVICE_TYPE_LE -> "低功耗蓝牙" BluetoothDevice.DEVICE_TYPE_DUAL -> "双模蓝牙" else -> "未知类型" } } private fun determineBluetoothBondState(type: Int): String { return when (type) { BluetoothDevice.BOND_NONE -> "未绑定" BluetoothDevice.BOND_BONDED -> "已绑定" BluetoothDevice.BOND_BONDING -> "绑定中" else -> "未知状态" } } private data class BluetoothInfo( val name: String, val address: String, val rssi: String, val type: String, val bondState: String, val uuids: List<String> )
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/Bluetooth.kt
2048576476
package top.chengdongqing.weui.feature.hardware.screens import android.hardware.Sensor import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.theme.FontSecondaryColorLight import top.chengdongqing.weui.core.utils.format import top.chengdongqing.weui.feature.hardware.compass.CompassViewModel import top.chengdongqing.weui.feature.hardware.compass.WeCompass import top.chengdongqing.weui.feature.hardware.utils.determineAccuracy import top.chengdongqing.weui.feature.hardware.utils.rememberSensorValue /** * 基于磁力计和加速度计实现的原因: * 1. 磁力计:这种传感器可以检测地球磁场的强度和方向。由于地球本身是一个巨大的磁体,磁力计可以用来确定手机相对于地球磁北极的方向。这是指南针功能的核心部分,因为它提供了指向地理北极(根据地球磁场)的基础方向信息。 * 2. 加速度计:虽然磁力计能提供方向信息,但它本身无法确定手机的倾斜状态(即手机是水平放置还是倾斜)。加速度计可以检测手机相对于地心引力的加速度,从而帮助判断手机的倾斜角度或方位。这对于调整指南针读数以适应用户在不同姿势(如站立、坐着或躺着)下使用手机时是非常重要的。 * 结合这两种传感器,手机能够提供更准确的方向信息。当你移动手机时,磁力计和加速度计的数据会被实时处理,以确保指南针指示的方向尽可能准确,无论设备的放置方式如何。这种组合使得手机上的指南针功能既实用又灵活,能够满足日常生活中对方向判断的需求。 */ @Composable fun CompassScreen(compassViewModel: CompassViewModel = viewModel()) { WeScreen(title = "Compass", description = "罗盘(指南针),基于磁力计与加速度计") { val pressure = rememberSensorValue(Sensor.TYPE_PRESSURE, compassViewModel.observing) WeCompass(compassViewModel) Spacer(modifier = Modifier.height(20.dp)) compassViewModel.accuracy?.let { Text( text = "精度:${determineAccuracy(it)}", color = FontSecondaryColorLight, fontSize = 10.sp ) } pressure?.let { Text( text = "气压:${pressure.format()}hPa(百帕斯卡)", color = MaterialTheme.colorScheme.onPrimary, fontSize = 10.sp ) } Spacer(modifier = Modifier.height(40.dp)) if (!compassViewModel.observing) { WeButton(text = "开始监听") { compassViewModel.observing = true } } else { WeButton(text = "取消监听", type = ButtonType.PLAIN) { compassViewModel.observing = false } } } }
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/Compass.kt
3627549425
package top.chengdongqing.weui.feature.hardware.screens import android.hardware.Sensor import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem import top.chengdongqing.weui.core.ui.components.cardlist.cartList import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.format import top.chengdongqing.weui.feature.hardware.utils.rememberSensorValues @Composable fun AccelerometerScreen() { WeScreen( title = "Accelerometer", description = "加速度计,用于测量加速度,包括重力加速度", scrollEnabled = false ) { val (observing, setObserving) = remember { mutableStateOf(false) } val values = rememberSensorValues(Sensor.TYPE_ACCELEROMETER, observing) if (!observing) { WeButton(text = "开始监听") { setObserving(true) } } else { WeButton(text = "取消监听", type = ButtonType.PLAIN) { setObserving(false) } } Spacer(modifier = Modifier.height(40.dp)) values?.let { Text( text = "单位:m/s²(米/秒平方)", color = MaterialTheme.colorScheme.onPrimary, fontSize = 10.sp ) Spacer(modifier = Modifier.height(20.dp)) LazyColumn(modifier = Modifier.cartList()) { itemsIndexed(it) { index, value -> WeCardListItem( label = "${getAxisLabel(index)}轴", value = value.format() ) } } } } } private fun getAxisLabel(index: Int): String { return when (index) { 0 -> "X" 1 -> "Y" 2 -> "Z" else -> "" } }
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/Accelerometer.kt
1873010028
package top.chengdongqing.weui.feature.hardware.screens import android.content.Context import android.hardware.ConsumerIrManager import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.components.toast.ToastIcon import top.chengdongqing.weui.core.ui.components.toast.rememberToastState @Composable fun InfraredScreen() { WeScreen(title = "Infrared", description = "红外信号") { val context = LocalContext.current val irManager = context.getSystemService(Context.CONSUMER_IR_SERVICE) as? ConsumerIrManager val toast = rememberToastState() WeButton("发射红外信号") { if (irManager?.hasIrEmitter() == true) { // 红外信号模式是由一系列以微秒为单位的整数构成的数组,这些整数代表红外信号的“开”和“关”持续时间 // 1.所有的值都要是正数 // 2.至少应有两个值(一个“开”和一个“关”),且值的数量应为偶数 val pattern = intArrayOf(9000, 4500, 560, 560) // 频率 val frequency = 38000 irManager.transmit(frequency, pattern) toast.show("已发射", ToastIcon.SUCCESS) } else { toast.show("此设备不支持红外", ToastIcon.FAIL) } } } }
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/Infrared.kt
26340556
package top.chengdongqing.weui.feature.hardware.screens import android.content.Context import android.content.Intent import android.nfc.NfcManager import android.provider.Settings import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.showToast @Composable fun NFCScreen() { WeScreen(title = "NFC", description = "近场通信") { val context = LocalContext.current val nfcManager = context.getSystemService(Context.NFC_SERVICE) as? NfcManager val nfcAdapter = nfcManager?.defaultAdapter WeButton(text = "扫描NFC") { if (nfcAdapter == null) { context.showToast("此设备不支持NFC") } else if (nfcAdapter.isEnabled) { context.showToast("示例待完善") } else { context.showToast("NFC未开启") context.startActivity(Intent(Settings.ACTION_NFC_SETTINGS)) } } } }
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/NFC.kt
2486457323
package top.chengdongqing.weui.feature.hardware.screens import android.content.Context import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CameraManager import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.components.switch.WeSwitch import top.chengdongqing.weui.core.utils.isTrue import top.chengdongqing.weui.core.utils.showToast @Composable fun FlashlightScreen() { WeScreen(title = "Flashlight", description = "闪光灯") { val context = LocalContext.current val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager val cameraId = rememberFlashAvailableCameraId(cameraManager) var isFlashOn by remember { mutableStateOf(false) } DisposableEffect(isFlashOn) { cameraId?.let { cameraManager.setTorchMode(cameraId, isFlashOn) } onDispose { if (isFlashOn && cameraId != null) { cameraManager.setTorchMode(cameraId, false) } } } WeSwitch(isFlashOn) { checked -> cameraId?.let { isFlashOn = checked } ?: context.showToast("此设备不支持闪光灯") } } } @Composable private fun rememberFlashAvailableCameraId(cameraManager: CameraManager): String? { return remember { cameraManager.cameraIdList.find { cameraManager.getCameraCharacteristics(it) .get(CameraCharacteristics.FLASH_INFO_AVAILABLE).isTrue() } } }
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/Flashlight.kt
1966930531
package top.chengdongqing.weui.feature.hardware.screens import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.location.GnssStatus import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.os.Handler import android.os.Looper import android.provider.Settings import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.cardlist.cartList import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.format import top.chengdongqing.weui.core.utils.formatDegree import top.chengdongqing.weui.core.utils.showToast @SuppressLint("MissingPermission") @OptIn(ExperimentalPermissionsApi::class) @Composable fun GNSSScreen() { WeScreen(title = "GNSS", description = "全球导航卫星系统", scrollEnabled = false) { val context = LocalContext.current val permissionState = rememberPermissionState(Manifest.permission.ACCESS_FINE_LOCATION) val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager val (observing, setObserving) = remember { mutableStateOf(false) } val (satelliteList, location) = rememberSatelliteList(locationManager, observing) val groupedList by remember { derivedStateOf { // 根据类型分组 satelliteList.groupBy { it.type }.mapValues { (_, value) -> // 根据编号排序 value.sortedBy { it.svid } } } } if (!observing) { WeButton(text = "开始扫描") { if (permissionState.status.isGranted) { if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { context.showToast("位置服务未开启") context.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) } else { setObserving(true) } } else { permissionState.launchPermissionRequest() } } } else { WeButton(text = "停止扫描", type = ButtonType.PLAIN) { setObserving(false) } } location?.let { LocationInfo(it, satelliteList.size) Spacer(modifier = Modifier.height(20.dp)) SatelliteTable(groupedList) } } } @Composable private fun LocationInfo(location: Location, satelliteCount: Int) { Spacer(modifier = Modifier.height(20.dp)) Text( text = buildString { appendLine("卫星数量:${satelliteCount}颗") val latitude = location.latitude.format(6) val longitude = location.longitude.format(6) appendLine("坐标:$latitude, $longitude") appendLine("海拔:${location.altitude.format()}m, 精度:${location.accuracy.format()}m") }, color = MaterialTheme.colorScheme.onPrimary, fontSize = 12.sp, textAlign = TextAlign.Center, lineHeight = 20.sp ) } @OptIn(ExperimentalFoundationApi::class) @Composable private fun SatelliteTable(groups: Map<String, List<SatelliteInfo>>) { LazyColumn(modifier = Modifier.cartList(PaddingValues(top = 20.dp))) { groups.forEach { (type, list) -> stickyHeader(key = type) { Column(modifier = Modifier.background(MaterialTheme.colorScheme.onBackground)) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { Text( text = type, color = MaterialTheme.colorScheme.onPrimary, fontSize = 12.sp ) } Spacer(modifier = Modifier.height(4.dp)) SatelliteTableRow( remember { listOf( "编号", "方位角", "高度角", "频点", "信号强度" ) }) Spacer(modifier = Modifier.height(5.dp)) } } items(list, key = { it.svid }) { SatelliteTableRow( listOf( it.svid.toString(), it.azimuthDegrees, it.elevationDegrees, it.frequency, "${it.signalStrength}dBHz" ) ) } item { Spacer(modifier = Modifier.height(20.dp)) } } } } @Composable private fun SatelliteTableRow(columns: List<String>) { Row(modifier = Modifier.fillMaxWidth()) { columns.forEach { Text( text = it, color = MaterialTheme.colorScheme.onPrimary, fontSize = 10.sp, textAlign = TextAlign.Center, modifier = Modifier.weight(1f) ) } } } @SuppressLint("MissingPermission") @Composable private fun rememberSatelliteList( locationManager: LocationManager, observing: Boolean ): Pair<List<SatelliteInfo>, Location?> { val satelliteList = remember { mutableStateListOf<SatelliteInfo>() } var location by remember { mutableStateOf<Location?>(null) } val satelliteStatusCallback = remember { SatelliteStatusCallback(satelliteList) } val locationListener = remember { LocationListener { location = it } } fun stopScan() { locationManager.removeUpdates(locationListener) locationManager.unregisterGnssStatusCallback(satelliteStatusCallback) } LaunchedEffect(observing) { if (observing) { locationManager.registerGnssStatusCallback( satelliteStatusCallback, Handler(Looper.getMainLooper()) ) locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 1000, // 多久更新一次 0f, // 移动超过多少米才更新 locationListener ) } else { stopScan() } } DisposableEffect(Unit) { onDispose { stopScan() } } return Pair(satelliteList, location) } private class SatelliteStatusCallback( val satelliteList: MutableList<SatelliteInfo> ) : GnssStatus.Callback() { override fun onSatelliteStatusChanged(status: GnssStatus) { val svidArray = Array(status.satelliteCount) { status.getSvid(it) } satelliteList.removeIf { !svidArray.contains(it.svid) } for (i in 0 until status.satelliteCount) { val info = SatelliteInfo( type = determineSatelliteType(status.getConstellationType(i)), svid = status.getSvid(i), azimuthDegrees = formatDegree(status.getAzimuthDegrees(i)), elevationDegrees = formatDegree(status.getElevationDegrees(i)), frequency = formatFrequency(status.getCarrierFrequencyHz(i)), signalStrength = status.getCn0DbHz(i) ) val index = satelliteList.indexOfFirst { it.svid == status.getSvid(i) } if (index != -1) { satelliteList[index] = info } else { satelliteList.add(info) } } satelliteList.removeIf { it.signalStrength == 0f } } } private fun formatFrequency(value: Float): String { // 截取前4位整数并留1位小数 var scaledValue = value while (scaledValue >= 10000) { scaledValue /= 10 } return "%.1f".format(scaledValue) } private fun determineSatelliteType(constellationType: Int): String { return when (constellationType) { GnssStatus.CONSTELLATION_BEIDOU -> "北斗(中国)" GnssStatus.CONSTELLATION_GPS -> "GPS(美国)" GnssStatus.CONSTELLATION_GLONASS -> "GLONASS(俄罗斯)" GnssStatus.CONSTELLATION_GALILEO -> "GALILEO(欧盟)" GnssStatus.CONSTELLATION_QZSS -> "QZSS(日本)" GnssStatus.CONSTELLATION_IRNSS -> "IRNSS(印度)" GnssStatus.CONSTELLATION_SBAS -> "SBAS(地面导航增强系统)" else -> "未知" } } private data class SatelliteInfo( /** * 类型 */ val type: String, /** * 编号 */ val svid: Int, /** * 方位角 */ val azimuthDegrees: String, /** * 高度角 */ val elevationDegrees: String, /** * 频点 */ val frequency: String, /** * 信号强度 */ val signalStrength: Float )
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/GNSS.kt
1787174833
package top.chengdongqing.weui.feature.hardware.screens import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.vibrateLong import top.chengdongqing.weui.core.utils.vibrateShort @Composable fun VibrationScreen() { WeScreen(title = "Vibration", description = "震动") { val context = LocalContext.current WeButton(text = "短震动") { context.vibrateShort() } Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "长震动", type = ButtonType.PLAIN) { context.vibrateLong() } } }
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/Vibration.kt
535556260
package top.chengdongqing.weui.feature.hardware.screens import android.app.Activity import android.content.Context import android.hardware.Sensor import android.provider.Settings import android.view.Window import android.view.WindowManager import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.components.slider.WeSlider import top.chengdongqing.weui.feature.hardware.utils.rememberSensorValue @Composable fun ScreenScreen() { WeScreen(title = "Screen", description = "屏幕") { val context = LocalContext.current val window = (context as Activity).window var screenBrightness by rememberScreenBrightness(window) val lightBrightness = rememberSensorValue(Sensor.TYPE_LIGHT, true) Box(modifier = Modifier.padding(horizontal = 12.dp)) { WeSlider( value = screenBrightness * 100, onChange = { screenBrightness = it / 100f setScreenBrightness(window, screenBrightness) } ) } Spacer(modifier = Modifier.height(20.dp)) Text( text = "光线强度:${lightBrightness} Lux(勒克斯)", color = MaterialTheme.colorScheme.onPrimary, fontSize = 10.sp ) Spacer(modifier = Modifier.height(40.dp)) KeepScreenOn(window) Spacer(modifier = Modifier.height(20.dp)) DisabledScreenshot(window) } } @Composable private fun KeepScreenOn(window: Window) { var value by remember { mutableStateOf(false) } WeButton(text = "${if (value) "取消" else "保持"}屏幕常亮") { value = !value if (value) { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } else { window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } } } @Composable private fun DisabledScreenshot(window: Window) { var value by remember { mutableStateOf(false) } WeButton( text = "${if (value) "取消" else "开启"}禁止截屏", type = ButtonType.PLAIN ) { value = !value if (value) { window.addFlags(WindowManager.LayoutParams.FLAG_SECURE) } else { window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) } } } @Composable private fun rememberScreenBrightness(window: Window): MutableState<Float> { val context = LocalContext.current val brightness = remember { mutableFloatStateOf(getScreenBrightness(context)) } DisposableEffect(Unit) { val initialValue = brightness.floatValue onDispose { setScreenBrightness(window, initialValue) } } return brightness } private fun getScreenBrightness(context: Context): Float { val brightness = Settings.System.getInt( context.contentResolver, Settings.System.SCREEN_BRIGHTNESS ) return brightness / 255f * 2 } private fun setScreenBrightness(window: Window, brightness: Float) { window.attributes = window.attributes.apply { screenBrightness = if (brightness > 1 || brightness < 0) -1f else brightness } }
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/Screen.kt
1779852269
package top.chengdongqing.weui.feature.hardware.screens import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.net.wifi.ScanResult import android.net.wifi.WifiManager import android.os.Build import android.provider.Settings import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Lock import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.rememberMultiplePermissionsState import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.cardlist.cartList import top.chengdongqing.weui.core.ui.components.divider.WeDivider import top.chengdongqing.weui.core.ui.components.loading.LoadMoreType import top.chengdongqing.weui.core.ui.components.loading.WeLoadMore import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.showToast @SuppressLint("MissingPermission") @OptIn(ExperimentalPermissionsApi::class) @Composable fun WiFiScreen() { WeScreen(title = "Wi-Fi", description = "无线局域网", scrollEnabled = false) { val context = LocalContext.current val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as? WifiManager var wifiList by remember { mutableStateOf<List<WiFiInfo>>(emptyList()) } val permissionState = rememberMultiplePermissionsState( remember { listOf( Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_FINE_LOCATION ) } ) WeButton(text = "扫描Wi-Fi") { if (permissionState.allPermissionsGranted) { if (wifiManager == null) { context.showToast("此设备不支持Wi-Fi") } else if (wifiManager.isWifiEnabled) { wifiList = buildWiFiList(wifiManager.scanResults) } else { context.showToast("Wi-Fi未开启") context.startActivity(Intent(Settings.ACTION_WIFI_SETTINGS)) } } else { permissionState.launchMultiplePermissionRequest() } } Spacer(modifier = Modifier.height(40.dp)) WiFiList(wifiList) } } @Composable private fun WiFiList(wifiList: List<WiFiInfo>) { if (wifiList.isNotEmpty()) { LazyColumn(modifier = Modifier.cartList()) { itemsIndexed(wifiList) { index, wifi -> WiFiListItem(wifi) if (index < wifiList.lastIndex) { WeDivider() } } } } else { WeLoadMore(type = LoadMoreType.ALL_LOADED) } } @Composable private fun WiFiListItem(wifi: WiFiInfo) { Row( modifier = Modifier .fillMaxWidth() .height(60.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Row(verticalAlignment = Alignment.CenterVertically) { Text(text = wifi.name, color = MaterialTheme.colorScheme.onPrimary) Spacer(modifier = Modifier.width(4.dp)) Text( text = wifi.band, color = MaterialTheme.colorScheme.onSecondary, fontSize = 10.sp, modifier = Modifier .border(0.5.dp, MaterialTheme.colorScheme.outline, RoundedCornerShape(3.dp)) .padding(horizontal = 3.dp) ) } Row(verticalAlignment = Alignment.CenterVertically) { if (wifi.secure) { Icon( imageVector = Icons.Filled.Lock, contentDescription = "加密", modifier = Modifier.size(20.dp), tint = MaterialTheme.colorScheme.onSecondary ) } Spacer(modifier = Modifier.width(8.dp)) Text( text = wifi.level, color = MaterialTheme.colorScheme.onPrimary, fontSize = 14.sp ) } } } private fun buildWiFiList(scanResultList: List<ScanResult>): List<WiFiInfo> { return scanResultList.sortedByDescending { it.level } .map { item -> WiFiInfo( name = getSSID(item), band = determineWifiBand(item.frequency), level = "${calculateSignalLevel(item.level)}%", secure = isWifiSecure(item.capabilities) ) } } private fun getSSID(wifi: ScanResult): String { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { wifi.wifiSsid?.bytes?.decodeToString() ?: "" } else { @Suppress("DEPRECATION") wifi.SSID } } private fun determineWifiBand(frequency: Int): String { return when (frequency) { in 2400..2500 -> "2.4G" in 4900..5900 -> "5G" in 5925..7125 -> "6G" else -> "未知频段" } } private fun calculateSignalLevel(rssi: Int, numLevels: Int = 100): Int { val minRssi = -100 val maxRssi = -55 if (rssi <= minRssi) { return 0 } else if (rssi >= maxRssi) { return numLevels - 1 } else { val inputRange = (maxRssi - minRssi).toFloat() val outputRange = (numLevels - 1).toFloat() return ((rssi - minRssi).toFloat() * outputRange / inputRange).toInt() } } private fun isWifiSecure(capabilities: String): Boolean { return capabilities.contains("WEP") || capabilities.contains("PSK") || capabilities.contains("EAP") } private data class WiFiInfo( val name: String, val band: String, val level: String, val secure: Boolean )
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/WiFi.kt
3365251655
package top.chengdongqing.weui.feature.hardware.screens import android.hardware.Sensor import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem import top.chengdongqing.weui.core.ui.components.cardlist.cartList import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.format import top.chengdongqing.weui.feature.hardware.utils.rememberSensorValues @Composable fun GyroscopeScreen() { WeScreen(title = "Gyroscope", description = "陀螺仪,用于测量旋转运动", scrollEnabled = false) { val (observing, setObserving) = remember { mutableStateOf(false) } val values = rememberSensorValues(Sensor.TYPE_GYROSCOPE, observing) if (!observing) { WeButton(text = "开始监听") { setObserving(true) } } else { WeButton(text = "取消监听", type = ButtonType.PLAIN) { setObserving(false) } } Spacer(modifier = Modifier.height(40.dp)) values?.let { Text( text = "单位:rad/s(弧度/秒)", color = MaterialTheme.colorScheme.onPrimary, fontSize = 10.sp ) Spacer(modifier = Modifier.height(20.dp)) LazyColumn(modifier = Modifier.cartList()) { itemsIndexed(it) { index, value -> WeCardListItem( label = "${getAxisLabel(index)}轴", value = value.format() ) } } } } } private fun getAxisLabel(index: Int): String { return when (index) { 0 -> "X" 1 -> "Y" 2 -> "Z" else -> "" } }
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/Gyroscope.kt
4017728490
package top.chengdongqing.weui.feature.hardware.screens import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG import androidx.biometric.BiometricPrompt import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.fragment.app.FragmentActivity import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.showToast @Composable fun FingerprintScreen() { WeScreen(title = "Fingerprint", description = "指纹认证") { val context = LocalContext.current WeButton(text = "指纹认证") { context.startActivity(BiometricActivity.newIntent(context)) } } } class BiometricActivity : FragmentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val promptInfo = BiometricPrompt.PromptInfo.Builder() .setTitle("指纹认证") .setAllowedAuthenticators(BIOMETRIC_STRONG) .setNegativeButtonText("取消认证") .build() createBiometricPrompt(this).authenticate(promptInfo) } companion object { fun newIntent(context: Context) = Intent(context, BiometricActivity::class.java) } } private fun createBiometricPrompt(activity: FragmentActivity): BiometricPrompt { val callback = object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { super.onAuthenticationError(errorCode, errString) activity.finish() activity.showToast(errString.toString()) } override fun onAuthenticationFailed() { super.onAuthenticationFailed() activity.showToast("认证失败") } override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { super.onAuthenticationSucceeded(result) activity.setResult(Activity.RESULT_OK) activity.finish() activity.showToast("认证成功") } } return BiometricPrompt(activity, callback) } // 使用旧API可以自定义界面样式,但安全性和兼容性需要自己控制 //class FingerprintViewModel(private val application: Application) : AndroidViewModel(application) { // // private lateinit var fingerprintManager: FingerprintManager // private lateinit var cancellationSignal: CancellationSignal // // fun initFingerprintManager(context: Context) { // fingerprintManager = // context.getSystemService(Context.FINGERPRINT_SERVICE) as FingerprintManager // startListening(null) // } // // private fun startListening(cryptoObject: FingerprintManager.CryptoObject?) { // cancellationSignal = CancellationSignal() // if (ActivityCompat.checkSelfPermission( // application, // Manifest.permission.USE_FINGERPRINT // ) != PackageManager.PERMISSION_GRANTED // ) { // return // } // fingerprintManager.authenticate( // cryptoObject, // cancellationSignal, // 0, // authenticationCallback, // null // ) // } // // private val authenticationCallback = object : FingerprintManager.AuthenticationCallback() { // override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { // super.onAuthenticationError(errorCode, errString) // // 处理错误情况 // application.showToast("出现错误") // } // // override fun onAuthenticationSucceeded(result: FingerprintManager.AuthenticationResult) { // super.onAuthenticationSucceeded(result) // // 认证成功 // application.showToast("认证成功") // } // // override fun onAuthenticationFailed() { // super.onAuthenticationFailed() // // 认证失败 // application.showToast("认证失败") // } // } // // fun cancelAuthentication() { // cancellationSignal.cancel() // } //}
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/Fingerprint.kt
2973550628
package top.chengdongqing.weui.feature.hardware.compass import android.content.Context import android.hardware.Sensor import android.hardware.SensorManager import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextMeasurer import androidx.compose.ui.text.drawText import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import top.chengdongqing.weui.core.utils.UpdatedEffect import top.chengdongqing.weui.core.utils.formatDegree import top.chengdongqing.weui.core.utils.polarToCartesian import top.chengdongqing.weui.core.utils.vibrateShort @Composable fun WeCompass(compassViewModel: CompassViewModel = viewModel()) { val context = LocalContext.current val degrees = compassViewModel.degrees val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager val accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) // 加速度计 val magnetometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) // 磁力计 LaunchedEffect(compassViewModel.observing) { if (compassViewModel.observing) { sensorManager.registerListener( compassViewModel.eventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_UI ) sensorManager.registerListener( compassViewModel.eventListener, magnetometerSensor, SensorManager.SENSOR_DELAY_UI ) } else { sensorManager.unregisterListener(compassViewModel.eventListener) } } DisposableEffect(Unit) { onDispose { sensorManager.unregisterListener(compassViewModel.eventListener) } } // 指向准点方位后触发震动 UpdatedEffect(degrees) { if (degrees % 90 == 0) { context.vibrateShort() } } CompassSurface(degrees) } @Composable private fun CompassSurface(degrees: Int) { val textMeasurer = rememberTextMeasurer() val colors = MaterialTheme.compassColorScheme Canvas( modifier = Modifier .size(300.dp) .fillMaxSize() ) { val center = Offset(size.width / 2, size.height / 2) val radius = size.minDimension / 2 drawCompassFace(center, radius, colors) drawCompassScales(center, radius, degrees, textMeasurer, colors) drawNorthIndicator(radius, colors.indicatorColor) drawCurrentDegrees(radius, degrees, textMeasurer, colors) } } // 绘制圆盘 private fun DrawScope.drawCompassFace(center: Offset, radius: Float, colors: CompassColors) { drawCircle( color = colors.containerColor, center = center, radius = radius ) } // 绘制罗盘的刻度和方位 private fun DrawScope.drawCompassScales( center: Offset, radius: Float, degrees: Int, textMeasurer: TextMeasurer, colors: CompassColors ) { for (angle in 0 until 360 step 10) { val angleRadians = Math.toRadians(angle.toDouble() - degrees - 90) drawScaleLine(center, radius, angle, angleRadians, colors) drawDegreeText(center, radius, angle, angleRadians, textMeasurer, colors) drawCardinalPoint(center, radius, angle, angleRadians, textMeasurer, colors) } } // 绘制刻度线 private fun DrawScope.drawScaleLine( center: Offset, radius: Float, angle: Int, angleRadians: Double, colors: CompassColors ) { val localRadius = radius - 8.dp.toPx() val startRadius = if (angle % 45 == 0) { localRadius - 10.dp.toPx() } else { localRadius - 8.dp.toPx() } val (startX, startY) = polarToCartesian(center, startRadius, angleRadians) val (endX, endY) = polarToCartesian(center, localRadius, angleRadians) drawLine( color = if (angle % 45 == 0) colors.scalePrimaryColor else colors.scaleSecondaryColor, start = Offset(startX, startY), end = Offset(endX, endY), strokeWidth = 1.dp.toPx() ) } // 绘制度数刻度 private fun DrawScope.drawDegreeText( center: Offset, radius: Float, angle: Int, angleRadians: Double, textMeasurer: TextMeasurer, colors: CompassColors ) { if (angle % 30 == 0) { val degreeText = AnnotatedString( angle.toString(), SpanStyle(fontSize = 12.sp) ) val textRadius = radius - 8.dp.toPx() - 26.dp.toPx() val (degreeX, degreeY) = polarToCartesian(center, textRadius, angleRadians) val textLayoutResult = textMeasurer.measure(degreeText) drawText( textLayoutResult, color = if (angle % 90 == 0) colors.scalePrimaryColor else colors.scaleSecondaryColor, topLeft = Offset( degreeX - textLayoutResult.size.width / 2, degreeY - textLayoutResult.size.height / 2 ) ) } } // 绘制方位文本 private fun DrawScope.drawCardinalPoint( center: Offset, radius: Float, angle: Int, angleRadians: Double, textMeasurer: TextMeasurer, colors: CompassColors ) { if (angle % 90 == 0) { val cardinalPoint = getCardinalPoint(angle) val textRadius = radius - 8.dp.toPx() - 60.dp.toPx() val (textX, textY) = polarToCartesian(center, textRadius, angleRadians) val text = AnnotatedString( cardinalPoint, SpanStyle(fontSize = 20.sp, fontWeight = FontWeight.Bold) ) val textLayoutResult = textMeasurer.measure(text) drawText( textLayoutResult, color = colors.fontColor, topLeft = Offset( textX - textLayoutResult.size.width / 2, textY - textLayoutResult.size.height / 2 ) ) } } // 绘制向北指针 private fun DrawScope.drawNorthIndicator(radius: Float, color: Color) { drawLine( color, Offset(x = radius, y = -8.dp.toPx()), Offset(x = radius, y = 18.dp.toPx()), strokeWidth = 3.dp.toPx(), cap = StrokeCap.Round ) } // 绘制当前度数 private fun DrawScope.drawCurrentDegrees( radius: Float, degrees: Int, textMeasurer: TextMeasurer, colors: CompassColors ) { val degreeText = AnnotatedString( formatDegree(degrees.toFloat(), 0), SpanStyle(fontSize = 40.sp, fontWeight = FontWeight.Bold) ) val textLayoutResult = textMeasurer.measure(degreeText) drawText( textLayoutResult, color = colors.fontColor, topLeft = Offset( radius - textLayoutResult.size.width / 2, radius - textLayoutResult.size.height / 2 ) ) } // 获取方位名称 private fun getCardinalPoint(angle: Int): String { return when (angle) { 0 -> "北" 90 -> "东" 180 -> "南" 270 -> "西" else -> "" } } private data class CompassColors( val containerColor: Color, val fontColor: Color, val scalePrimaryColor: Color, val scaleSecondaryColor: Color, val indicatorColor: Color ) private val MaterialTheme.compassColorScheme: CompassColors @Composable get() = CompassColors( containerColor = colorScheme.onBackground, fontColor = colorScheme.onPrimary, scalePrimaryColor = colorScheme.onSecondary, scaleSecondaryColor = colorScheme.outline, indicatorColor = colorScheme.primary )
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/compass/Compass.kt
3397295832
package top.chengdongqing.weui.feature.hardware.compass import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel class CompassViewModel : ViewModel() { var degrees by mutableIntStateOf(0) private set var accuracy by mutableStateOf<Int?>(null) private set var observing by mutableStateOf(false) val eventListener by lazy { CompassEventListener( onDegreesChange = { degrees = it }, onAccuracyChange = { accuracy = it } ) } } class CompassEventListener( val onDegreesChange: (Int) -> Unit, val onAccuracyChange: (Int) -> Unit ) : SensorEventListener { private var gravity: FloatArray? = null private var geomagnetic: FloatArray? = null override fun onSensorChanged(event: SensorEvent) { when (event.sensor.type) { Sensor.TYPE_ACCELEROMETER -> gravity = event.values.clone() Sensor.TYPE_MAGNETIC_FIELD -> geomagnetic = event.values.clone() } if (gravity != null && geomagnetic != null) { val r = FloatArray(9) val i = FloatArray(9) val success = SensorManager.getRotationMatrix(r, i, gravity, geomagnetic) if (success) { val orientation = FloatArray(3) SensorManager.getOrientation(r, orientation) var azimuth = Math.toDegrees(orientation.first().toDouble()) if (azimuth < 0) { azimuth += 360 } onDegreesChange(azimuth.toInt()) } } } override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) { if (sensor.type == Sensor.TYPE_MAGNETIC_FIELD) { onAccuracyChange(accuracy) } } }
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/compass/CompassViewModel.kt
2897692147
package top.chengdongqing.weui.feature.location.picker import android.app.Activity import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import top.chengdongqing.weui.core.ui.theme.WeUITheme import top.chengdongqing.weui.feature.location.data.model.LocationItem class LocationPickerActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { WeUITheme { WeLocationPicker(onCancel = { finish() }) { location -> val intent = Intent().apply { putExtra("location", location) } setResult(RESULT_OK, intent) finish() } } } } companion object { fun newIntent(context: Context) = Intent(context, LocationPickerActivity::class.java) } } @Composable fun rememberPickLocationLauncher(onChange: (LocationItem) -> Unit): () -> Unit { val context = LocalContext.current val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.StartActivityForResult() ) { result -> if (result.resultCode == Activity.RESULT_OK) { result.data?.apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { getParcelableExtra("location", LocationItem::class.java)?.let(onChange) } else { @Suppress("DEPRECATION") (getParcelableExtra("location") as? LocationItem)?.let(onChange) } } } } return { launcher.launch(LocationPickerActivity.newIntent(context)) } }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/picker/LocationPickerActivity.kt
2225824964
package top.chengdongqing.weui.feature.location.picker.locationlist import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.KeyboardArrowDown import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.unit.dp import com.amap.api.maps.CameraUpdateFactory import top.chengdongqing.weui.core.ui.components.searchbar.WeSearchBar import top.chengdongqing.weui.feature.location.picker.LocationPickerState @Composable fun SearchableLocationList(state: LocationPickerState, listState: LazyListState) { val animatedHeightFraction = animateFloatAsState( targetValue = if (state.isListExpanded) 0.7f else 0.4f, label = "LocationListHeightAnimation" ) val nestedScrollConnection = remember(state) { LocationListNestedScrollConnection( state, animatedHeightFraction ) } Column( modifier = Modifier .fillMaxWidth() .fillMaxHeight(animatedHeightFraction.value) .expandedStyle(state.isListExpanded) .background(MaterialTheme.colorScheme.surface) .nestedScroll(nestedScrollConnection) ) { if (state.isListExpanded) { TopArrow(state) } if (state.isSearchMode) { SearchPanel(state) } else { SearchInput(state) LocationList( listState, state.paging, state.selectedIndex, onSelect = { // 保存选择的位置索引 state.selectedIndex = it // 移动地图中心点到选中的位置 val latLng = state.paging.dataList[it].latLng state.map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16f)) } ) { if (!state.paging.isAllLoaded && !state.paging.isLoading) { val pageNum = state.paging.startLoadMore() state.search(state.mapCenterLatLng, pageNum = pageNum) .apply { val filteredList = this.filter { item -> state.paging.dataList.none { it.name == item.name } } state.paging.endLoadMore(filteredList) } } } } } } @Composable private fun ColumnScope.TopArrow(state: LocationPickerState) { Box( modifier = Modifier .align(Alignment.CenterHorizontally) .padding(top = 16.dp) .clip(RoundedCornerShape(20.dp)) .background(MaterialTheme.colorScheme.background) .clickable { state.isListExpanded = false } .padding(horizontal = 12.dp) ) { Icon( imageVector = Icons.Outlined.KeyboardArrowDown, contentDescription = null, tint = MaterialTheme.colorScheme.onSecondary, modifier = Modifier.size(22.dp) ) } } private fun Modifier.expandedStyle(expanded: Boolean) = if (expanded) { this .offset(y = (-12).dp) .clip(RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp)) } else { this } @Composable private fun SearchInput(state: LocationPickerState) { WeSearchBar( value = "", modifier = Modifier.padding(16.dp), placeholder = "搜索地点", disabled = true, onClick = { state.isSearchMode = true } ) {} } private class LocationListNestedScrollConnection( private val state: LocationPickerState, private val heightFraction: State<Float>, ) : NestedScrollConnection { override fun onPreScroll( available: Offset, source: NestedScrollSource ): Offset { if (available.y < 0 && !state.isListExpanded) { state.isListExpanded = true } return if (heightFraction.value == 0.7f) Offset.Zero else available } override fun onPostScroll( consumed: Offset, available: Offset, source: NestedScrollSource ): Offset { if (available.y > 0 && state.isListExpanded) { state.isListExpanded = false } return Offset.Zero } }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/picker/locationlist/SearchableLocationList.kt
1915418465
package top.chengdongqing.weui.feature.location.picker.locationlist import androidx.compose.animation.core.animateDpAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.unit.dp import com.amap.api.maps.CameraUpdateFactory import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.filter import top.chengdongqing.weui.core.ui.components.searchbar.WeSearchBar import top.chengdongqing.weui.core.utils.UpdatedEffect import top.chengdongqing.weui.core.utils.clickableWithoutRipple import top.chengdongqing.weui.core.utils.rememberKeyboardHeight import top.chengdongqing.weui.feature.location.data.model.LocationItem import top.chengdongqing.weui.feature.location.picker.LocationPickerState @Composable fun SearchPanel(state: LocationPickerState) { val listState = rememberLazyListState() val paging = state.pagingOfSearch val keywordFlow = remember { MutableStateFlow("") } val keyword by keywordFlow.collectAsState() var type by remember { mutableIntStateOf(0) } SearchingEffect(keywordFlow, state, paging, listState, keyword, type) KeyboardEffect(state) Column { WeSearchBar( value = keyword, modifier = Modifier.padding(16.dp), focused = true, onFocusChange = { if (!it) { state.isSearchMode = false } } ) { keywordFlow.value = it } TypeTabRow(type) { type = it } LocationList( listState, paging, state.selectedIndexOfSearch, onSelect = { // 保存选择的位置索引 state.selectedIndexOfSearch = it // 移动地图中心点到选中的位置 val latLng = paging.dataList[it].latLng state.map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16f)) // 选择位置后展开地图 state.isListExpanded = false } ) { if (!paging.isAllLoaded && !state.paging.isLoading) { val pageNum = paging.startLoadMore() state.search( location = if (type == 0) state.currentLatLng else null, keyword = keyword, pageNum = pageNum ).apply { val filteredList = this.filter { item -> paging.dataList.none { it.name == item.name } } paging.endLoadMore(filteredList) } } } } } @Composable private fun TypeTabRow(type: Int, onChange: (Int) -> Unit) { val options = remember { listOf("附近", "不限") } var itemWidth by remember { mutableStateOf(0.dp) } val density = LocalDensity.current Column(modifier = Modifier.padding(horizontal = 16.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { options.forEachIndexed { index, item -> val active = index == type Text( text = item, color = if (active) { MaterialTheme.colorScheme.primary } else { MaterialTheme.colorScheme.onPrimary }, modifier = Modifier .onSizeChanged { itemWidth = with(density) { it.width.toDp() } } .clickableWithoutRipple { onChange(index) } .padding(vertical = 3.dp) ) } } val animatedOffsetX by animateDpAsState( (type * itemWidth.value + type * 16).dp, label = "" ) HorizontalDivider( modifier = Modifier .width(itemWidth) .offset(x = animatedOffsetX), thickness = 2.dp, color = MaterialTheme.colorScheme.primary ) Spacer(modifier = Modifier.height(16.dp)) } } @OptIn(FlowPreview::class) @Composable private fun SearchingEffect( keywordFlow: Flow<String>, state: LocationPickerState, paging: PagingState<LocationItem>, listState: LazyListState, keyword: String, type: Int ) { val currentKeyword by rememberUpdatedState(newValue = keyword) val currentType by rememberUpdatedState(newValue = type) LaunchedEffect(keywordFlow) { keywordFlow .debounce(300) .filter { it.isNotBlank() } .collect { refresh(state, paging, listState, it, currentType) } } UpdatedEffect(currentType) { refresh(state, paging, listState, currentKeyword, currentType) } } private suspend fun refresh( state: LocationPickerState, paging: PagingState<LocationItem>, listState: LazyListState, keyword: String, type: Int ) { state.selectedIndexOfSearch = null if (keyword.isNotBlank()) { paging.startRefresh() state.search( location = if (type == 0) state.currentLatLng else null, keyword = keyword ).apply { paging.endRefresh(this) } listState.scrollToItem(0) } else { paging.dataList = emptyList() } } @Composable private fun KeyboardEffect(state: LocationPickerState) { val keyboardController = LocalSoftwareKeyboardController.current val keyboardHeight = rememberKeyboardHeight() UpdatedEffect(keyboardHeight) { if (keyboardHeight > 0.dp) { state.isListExpanded = true } } UpdatedEffect(state.isListExpanded) { if (!state.isListExpanded) { keyboardController?.hide() } } }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/picker/locationlist/SearchPanel.kt
3303294761
package top.chengdongqing.weui.feature.location.picker.locationlist import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import top.chengdongqing.weui.core.ui.components.R import top.chengdongqing.weui.core.ui.components.divider.WeDivider import top.chengdongqing.weui.core.ui.components.loading.LoadMoreType import top.chengdongqing.weui.core.ui.components.loading.WeLoadMore import top.chengdongqing.weui.core.ui.components.loading.WeLoading import top.chengdongqing.weui.core.ui.components.refreshview.rememberLoadMoreState import top.chengdongqing.weui.core.utils.clickableWithoutRipple import top.chengdongqing.weui.core.utils.formatDistance import top.chengdongqing.weui.feature.location.data.model.LocationItem @Composable fun LocationList( listState: LazyListState, pagingState: PagingState<LocationItem>, selectedIndex: Int?, onSelect: (Int) -> Unit, onLoadMore: suspend () -> Unit ) { val loadMoreState = rememberLoadMoreState( enabled = { !pagingState.isAllLoaded }, onLoadMore ) Box(modifier = Modifier.nestedScroll(loadMoreState.nestedScrollConnection)) { LazyColumn(state = listState, contentPadding = PaddingValues(bottom = 16.dp)) { itemsIndexed( pagingState.dataList, key = { _, item -> item.id ?: item.name } ) { index, item -> LocationListItem(index == selectedIndex, item) { onSelect(index) } if (index < pagingState.dataList.lastIndex) { WeDivider() } } item { if (loadMoreState.isLoadingMore) { WeLoadMore(listState = listState) } else if (pagingState.isAllLoaded) { WeLoadMore(type = LoadMoreType.ALL_LOADED) } } } if (pagingState.isLoading && !loadMoreState.isLoadingMore) { Box( modifier = Modifier .fillMaxWidth() .padding(top = 80.dp), contentAlignment = Alignment.Center ) { WeLoading(size = 80.dp) } } } } @Composable private fun LocationListItem(checked: Boolean, location: LocationItem, onClick: () -> Unit) { Row( modifier = Modifier .fillMaxWidth() .clickableWithoutRipple { onClick() } .padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically ) { Column(modifier = Modifier.weight(1f)) { Text( text = location.name, color = MaterialTheme.colorScheme.onPrimary, fontSize = 17.sp ) Spacer(modifier = Modifier.height(4.dp)) Text( text = buildList { location.distance?.let { add(formatDistance(it)) } location.address?.let { add(it) } }.joinToString(" | "), color = MaterialTheme.colorScheme.onSecondary, fontSize = 14.sp ) } if (checked) { Icon( painter = painterResource(id = R.drawable.ic_check), contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(24.dp) ) } } }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/picker/locationlist/LocationList.kt
1124898938
package top.chengdongqing.weui.feature.location.picker.locationlist import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue @Stable interface PagingState<T> { var dataList: List<T> val pageNumber: Int val pageSize: Int val isLoading: Boolean val isAllLoaded: Boolean fun startRefresh() fun endRefresh(dataList: List<T>) fun startLoadMore(): Int fun endLoadMore(dataList: List<T>) } class PagingStateImpl<T>( override val pageSize: Int = 10, initialLoading: Boolean = false ) : PagingState<T> { override var dataList by mutableStateOf<List<T>>(emptyList()) override var pageNumber by mutableIntStateOf(1) override var isLoading by mutableStateOf(initialLoading) override var isAllLoaded by mutableStateOf(false) override fun startRefresh() { isLoading = true pageNumber = 1 } override fun endRefresh(dataList: List<T>) { this.dataList = dataList isAllLoaded = dataList.size < pageSize if (!isAllLoaded) { pageNumber++ } isLoading = false } override fun startLoadMore(): Int { isLoading = true return pageNumber } override fun endLoadMore(dataList: List<T>) { this.dataList += dataList.also { if (it.isNotEmpty()) { pageNumber++ } isAllLoaded = it.size < pageSize } isLoading = false } }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/picker/locationlist/PagingState.kt
938845446
package top.chengdongqing.weui.feature.location.picker import android.view.MotionEvent import androidx.compose.foundation.lazy.LazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import com.amap.api.maps.AMap import com.amap.api.maps.CameraUpdateFactory import com.amap.api.maps.model.LatLng import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import top.chengdongqing.weui.feature.location.data.model.LocationItem import top.chengdongqing.weui.feature.location.data.repository.LocationRepository import top.chengdongqing.weui.feature.location.data.repository.LocationRepositoryImpl import top.chengdongqing.weui.feature.location.picker.locationlist.PagingState import top.chengdongqing.weui.feature.location.picker.locationlist.PagingStateImpl import top.chengdongqing.weui.feature.location.utils.isLoaded import top.chengdongqing.weui.feature.location.utils.toLatLng @Stable interface LocationPickerState { /** * 地图实例 */ val map: AMap /** * 当前设备坐标 */ val currentLatLng: LatLng? /** * 地图中心点坐标 */ var mapCenterLatLng: LatLng? /** * 是否是搜索模式 */ var isSearchMode: Boolean /** * 是否展开列表 */ var isListExpanded: Boolean /** * 分页信息 */ val paging: PagingState<LocationItem> /** * 选中的位置索引 */ var selectedIndex: Int /** * 搜索模式下的分页信息 */ val pagingOfSearch: PagingState<LocationItem> /** * 搜索模式下选中的位置索引 */ var selectedIndexOfSearch: Int? /** * 当前选中的位置信息 */ val selectedLocation: LocationItem? /** * 搜索位置 */ suspend fun search( location: LatLng?, keyword: String = "", pageNum: Int = 1, pageSize: Int = 10 ): List<LocationItem> } @Composable fun rememberLocationPickerState(map: AMap, listState: LazyListState): LocationPickerState { val context = LocalContext.current val coroutineScope = rememberCoroutineScope() val locationRepository = remember { LocationRepositoryImpl(context) } val currentLocation = locationRepository.currentLocation.collectAsState(initial = null) val state = remember { LocationPickerStateImpl( map, locationRepository, coroutineScope, currentLocation, listState ) } // 恢复上次缓存的位置信息 LaunchedEffect(currentLocation.value) { currentLocation.value?.let { if (state.mapCenterLatLng == null) { map.animateCamera(CameraUpdateFactory.newLatLngZoom(it, 16f)) state.mapCenterLatLng = it } } } return state } private class LocationPickerStateImpl( override val map: AMap, private val locationRepository: LocationRepository, private val coroutineScope: CoroutineScope, private val _currentLatLng: State<LatLng?>, private val listState: LazyListState ) : LocationPickerState { override var currentLatLng: LatLng? get() = _currentLatLng.value set(value) { value?.let { coroutineScope.launch { // 缓存到datastore,方便再次进入时快速获取定位 locationRepository.saveCurrentLocation(it) } } } override var mapCenterLatLng: LatLng? get() = _mapCenterLatLng set(value) { _mapCenterLatLng = value // 退出搜索模式 if (isSearchMode) { isSearchMode = false } if (value != null) { // 重置选中项 selectedIndex = 0 // 准备刷新 paging.startRefresh() coroutineScope.launch { // 获取地图中心点的位置信息,转为列表是方便和之后附近的位置列表合并 val centerLocationList = locationToAddress(value)?.let { listOf(it) } ?: emptyList() // 搜索附近位置信息 search(value).apply { paging.endRefresh(centerLocationList + this) } // 滚动到第一项 listState.scrollToItem(0) } } } override var isSearchMode: Boolean get() = _isSearchMode set(value) { _isSearchMode = value isListExpanded = value if (!value) { // 重置搜索结果 pagingOfSearch.dataList = emptyList() // 恢复地图视野 mapCenterLatLng?.let { map.animateCamera(CameraUpdateFactory.newLatLngZoom(it, 16f)) } } } override var isListExpanded by mutableStateOf(false) override val paging = PagingStateImpl<LocationItem>(initialLoading = true) override var selectedIndex by mutableIntStateOf(0) override val pagingOfSearch = PagingStateImpl<LocationItem>() override var selectedIndexOfSearch by mutableStateOf<Int?>(null) override val selectedLocation: LocationItem? get() { return if (!isSearchMode) { paging.dataList.getOrNull(selectedIndex) } else { selectedIndexOfSearch?.let { pagingOfSearch.dataList.getOrNull(it) } } } private var _mapCenterLatLng by mutableStateOf<LatLng?>(null) private var _isSearchMode by mutableStateOf(false) override suspend fun search( location: LatLng?, keyword: String, pageNum: Int, pageSize: Int ): List<LocationItem> { if (location == null && keyword.isBlank()) { return emptyList() } return locationRepository.search( location, keyword, pageNum, pageSize, currentLatLng ) } init { setMapClickAndDragListener() setLocationChangeListener() } private suspend fun locationToAddress(latLng: LatLng): LocationItem? { return locationRepository.locationToAddress(latLng)?.let { val address = it.formatAddress val startIndex = address.lastIndexOf(it.district) val name = address.slice(startIndex..address.lastIndex) LocationItem( name = name, address = address, latLng = latLng ) } } // 监听地图点击或拖拽事件 private fun setMapClickAndDragListener() { map.setOnMapClickListener { map.animateCamera(CameraUpdateFactory.newLatLng(it)) mapCenterLatLng = it } map.setOnPOIClickListener { map.animateCamera(CameraUpdateFactory.newLatLng(it.coordinate)) mapCenterLatLng = it.coordinate } map.setOnMapTouchListener { if (it.action == MotionEvent.ACTION_UP && !isSearchMode) { mapCenterLatLng = map.cameraPosition.target } } } // 监听当前位置变化 private fun setLocationChangeListener() { map.setOnMyLocationChangeListener { location -> if (location.isLoaded()) { location.toLatLng().let { // 只有在当前位置为空且非搜索模式时才将地图视野移至当前位置 if (currentLatLng == null && !isSearchMode) { map.animateCamera(CameraUpdateFactory.newLatLngZoom(it, 16f)) mapCenterLatLng = it } currentLatLng = it } } } } }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/picker/LocationPickerState.kt
330641194
package top.chengdongqing.weui.feature.location.picker import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.TweenSpec import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.amap.api.maps.model.MarkerOptions import top.chengdongqing.weui.core.ui.components.R import top.chengdongqing.weui.core.ui.components.button.ButtonSize import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.utils.clickableWithoutRipple import top.chengdongqing.weui.feature.location.AMap import top.chengdongqing.weui.feature.location.LocationControl import top.chengdongqing.weui.feature.location.data.model.LocationItem import top.chengdongqing.weui.feature.location.picker.locationlist.SearchableLocationList import top.chengdongqing.weui.feature.location.rememberAMapState import top.chengdongqing.weui.feature.location.utils.createBitmapDescriptor @Composable fun WeLocationPicker( onCancel: () -> Unit, onConfirm: (LocationItem) -> Unit ) { val mapState = rememberAMapState() val listState = rememberLazyListState() val state = rememberLocationPickerState(mapState.map, listState) Column(modifier = Modifier.fillMaxSize()) { Box(modifier = Modifier.weight(1f)) { AMap(state = mapState) { map -> LocationControl(map) { state.mapCenterLatLng = it } } TopBar( hasSelected = state.selectedLocation != null, onCancel ) { onConfirm(state.selectedLocation!!) } LocationMarker(state) } Box(modifier = Modifier.background(MaterialTheme.colorScheme.surface)) { SearchableLocationList(state, listState) } } } @Composable private fun BoxScope.LocationMarker(state: LocationPickerState) { if (!state.isSearchMode) { val offsetY = remember { Animatable(0f) } val animationSpec = remember { TweenSpec<Float>(durationMillis = 300) } LaunchedEffect(state.mapCenterLatLng) { offsetY.animateTo(-10f, animationSpec) offsetY.animateTo(0f, animationSpec) } Image( painter = painterResource(id = R.drawable.ic_location_marker), contentDescription = null, modifier = Modifier .align(Alignment.Center) .size(50.dp) .offset(y = (-25).dp + offsetY.value.dp) ) } else if (state.selectedLocation != null) { val context = LocalContext.current DisposableEffect(state.selectedLocation) { val markerOptions = MarkerOptions().apply { position(state.selectedLocation?.latLng) icon( createBitmapDescriptor( context, R.drawable.ic_location_marker, 160, 160 ) ) } val marker = state.map.addMarker(markerOptions) onDispose { marker?.remove() } } } } @Composable private fun TopBar(hasSelected: Boolean, onCancel: () -> Unit, onConfirm: () -> Unit) { Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .shadow(elevation = 100.dp) .statusBarsPadding() .padding(horizontal = 16.dp, vertical = 8.dp) ) { Text( text = "取消", color = Color.White, fontSize = 16.sp, modifier = Modifier.clickableWithoutRipple { onCancel() } ) WeButton( text = "确定", size = ButtonSize.SMALL, disabled = !hasSelected ) { onConfirm() } } }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/picker/LocationPicker.kt
2771929141
package top.chengdongqing.weui.feature.location.navigation import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import top.chengdongqing.weui.feature.location.screens.LocationPickerScreen import top.chengdongqing.weui.feature.location.screens.LocationPreviewScreen fun NavGraphBuilder.addLocationGraph() { composable("location_preview") { LocationPreviewScreen() } composable("location_picker") { LocationPickerScreen() } }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/navigation/LocationGraph.kt
2462646150
package top.chengdongqing.weui.feature.location.utils import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas import android.location.Location import android.net.Uri import android.os.Build import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat import com.amap.api.maps.model.BitmapDescriptor import com.amap.api.maps.model.BitmapDescriptorFactory import com.amap.api.maps.model.LatLng import com.amap.api.services.core.LatLonPoint import top.chengdongqing.weui.core.utils.showToast import top.chengdongqing.weui.feature.location.data.model.MapType import java.net.URLEncoder /** * 调用地图软件导航到指定位置 */ fun Context.navigateToLocation( mapType: MapType, location: LatLng, name: String ) { val uri: Uri = when (mapType) { MapType.AMAP -> { Uri.parse("amapuri://route/plan?dlat=${location.latitude}&dlon=${location.longitude}&dname=$name") } MapType.BAIDU -> { val encodedName = URLEncoder.encode(name, "UTF-8") Uri.parse("baidumap://map/direction?destination=latlng:${location.latitude},${location.longitude}|name:$encodedName") } MapType.TENCENT -> { Uri.parse("qqmap://map/routeplan?to=$name&tocoord=${location.latitude},${location.longitude}") } MapType.GOOGLE -> { Uri.parse("google.navigation:q=${location.latitude},${location.longitude}") } } val intent = Intent(Intent.ACTION_VIEW, uri) if (intent.resolveActivity(packageManager) != null) { startActivity(intent) } else { showToast("未安装${mapType.appName}地图") } } /** * 将指定的图片资源转为地图支持的bitmap * 支持指定宽高、旋转角度 */ fun createBitmapDescriptor( context: Context, @DrawableRes iconId: Int, width: Int? = null, height: Int? = null, rotationAngle: Float? = null ): BitmapDescriptor? { val drawable = ContextCompat.getDrawable(context, iconId) ?: return null val originalWidth = width ?: drawable.intrinsicWidth val originalHeight = height ?: drawable.intrinsicHeight val bitmap = Bitmap.createBitmap( originalWidth, originalHeight, Bitmap.Config.ARGB_8888 ) val canvas = Canvas(bitmap) // 旋转 rotationAngle?.let { val pivotX = originalWidth / 2f val pivotY = originalHeight / 2f canvas.save() // 保存画布当前的状态 canvas.rotate(it, pivotX, pivotY) // 应用旋转 } drawable.setBounds(0, 0, originalWidth, originalHeight) drawable.draw(canvas) // 如果旋转了画布,现在恢复到之前保存的状态 rotationAngle?.let { canvas.restore() } return BitmapDescriptorFactory.fromBitmap(bitmap) } // 判断位置是否加载完成 fun Location.isLoaded() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { this.isComplete } else { this.latitude != 0.0 && this.longitude != 0.0 } fun LatLonPoint.toLatLng() = LatLng(latitude, longitude) fun LatLng.toLatLonPoint() = LatLonPoint(latitude, longitude) fun Location.toLatLng() = LatLng(latitude, longitude)
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/utils/MapUtils.kt
1841340054
package top.chengdongqing.weui.feature.location.screens import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.amap.api.maps.model.LatLng import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem import top.chengdongqing.weui.core.ui.components.cardlist.cartList import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.feature.location.data.model.LocationPreviewItem import top.chengdongqing.weui.feature.location.preview.previewLocation @Composable fun LocationPreviewScreen() { WeScreen(title = "LocationPreview", description = "查看位置", scrollEnabled = false) { val context = LocalContext.current val location = remember { LocationPreviewItem( name = "庐山国家级旅游风景名胜区", address = "江西省九江市庐山市牯岭镇", latLng = LatLng(29.5628, 115.9928), zoom = 12f ) } LazyColumn(modifier = Modifier.cartList()) { item { location.apply { WeCardListItem(label = "纬度", value = latLng.latitude.toString()) WeCardListItem(label = "经度", value = latLng.longitude.toString()) WeCardListItem(label = "位置名称", value = name) WeCardListItem(label = "详细位置", value = address) } } } Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "查看位置") { context.previewLocation(location) } } }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/screens/LocationPreview.kt
1809982875
package top.chengdongqing.weui.feature.location.screens import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem import top.chengdongqing.weui.core.ui.components.cardlist.cartList import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.feature.location.data.model.LocationItem import top.chengdongqing.weui.feature.location.picker.rememberPickLocationLauncher @Composable fun LocationPickerScreen() { WeScreen(title = "LocationPicker", description = "选择位置", scrollEnabled = false) { var location by remember { mutableStateOf<LocationItem?>(null) } location?.apply { LazyColumn(modifier = Modifier.cartList()) { item { WeCardListItem(label = "纬度", value = latLng.latitude.toString()) WeCardListItem(label = "经度", value = latLng.longitude.toString()) WeCardListItem(label = "位置名称", value = name) WeCardListItem(label = "详细位置", value = address ?: "") } } Spacer(modifier = Modifier.height(20.dp)) } val pickLocation = rememberPickLocationLauncher { location = it } WeButton(text = "选择位置") { pickLocation() } } }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/screens/LocationPicker.kt
4042184178
package top.chengdongqing.weui.feature.location import android.Manifest import android.content.ComponentCallbacks import android.content.Context import android.content.res.Configuration import android.graphics.Color import android.os.Bundle import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.MyLocation import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.Stable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import com.amap.api.maps.AMap import com.amap.api.maps.AMapOptions import com.amap.api.maps.CameraUpdateFactory import com.amap.api.maps.MapView import com.amap.api.maps.MapsInitializer import com.amap.api.maps.model.LatLng import com.amap.api.maps.model.MyLocationStyle import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import top.chengdongqing.weui.core.ui.components.R import top.chengdongqing.weui.core.utils.isTrue import top.chengdongqing.weui.core.utils.showToast import top.chengdongqing.weui.feature.location.utils.createBitmapDescriptor import top.chengdongqing.weui.feature.location.utils.isLoaded import top.chengdongqing.weui.feature.location.utils.toLatLng @Composable fun AMap( modifier: Modifier = Modifier, state: AMapState = rememberAMapState(), controls: @Composable BoxScope.(AMap) -> Unit = { LocationControl(it) } ) { val context = LocalContext.current // 处理生命周期 LifecycleEffect(state.mapView) // 处理定位权限 PermissionHandler { setLocationArrow(state.map, context) } Box(modifier) { AndroidView( factory = { state.mapView }, modifier = Modifier.fillMaxSize() ) controls(state.map) } } @Composable fun BoxScope.LocationControl(map: AMap, onClick: ((LatLng) -> Unit)? = null) { val context = LocalContext.current Box( modifier = Modifier .align(Alignment.BottomStart) .offset(x = 12.dp, y = (-36).dp) .size(40.dp) .clip(RoundedCornerShape(8.dp)) .background(MaterialTheme.colorScheme.onBackground) .clickable { map.apply { if (myLocation ?.isLoaded() .isTrue() ) { val latLng = myLocation.toLatLng() animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16f)) onClick?.invoke(latLng) } else { context.showToast("定位中...") } } }, contentAlignment = Alignment.Center ) { Icon( imageVector = Icons.Outlined.MyLocation, contentDescription = "当前位置", tint = MaterialTheme.colorScheme.onPrimary, modifier = Modifier.size(26.dp) ) } } private fun setLocationArrow(map: AMap, context: Context) { map.apply { myLocationStyle = MyLocationStyle().apply { // 设置定位频率 interval(5000) // 设置定位类型 myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER) // 设置定位图标 val icon = createBitmapDescriptor( context, R.drawable.ic_location_rotatable, 90, 90, -60f ) myLocationIcon(icon) // 去除精度圆圈 radiusFillColor(Color.TRANSPARENT) strokeWidth(0f) } isMyLocationEnabled = true } } @OptIn(ExperimentalPermissionsApi::class) @Composable private fun PermissionHandler(onGranted: (() -> Unit)? = null) { val permissionState = rememberPermissionState(Manifest.permission.ACCESS_FINE_LOCATION) { if (it) { onGranted?.invoke() } } LaunchedEffect(Unit) { if (!permissionState.status.isGranted) { permissionState.launchPermissionRequest() } else { onGranted?.invoke() } } } @Composable private fun LifecycleEffect(mapView: MapView) { val context = LocalContext.current val lifecycle = LocalLifecycleOwner.current.lifecycle val previousState = remember { mutableStateOf(Lifecycle.Event.ON_CREATE) } DisposableEffect(context, lifecycle, mapView) { val mapLifecycleObserver = mapView.lifecycleObserver(previousState) val callbacks = mapView.componentCallbacks() lifecycle.addObserver(mapLifecycleObserver) context.registerComponentCallbacks(callbacks) onDispose { lifecycle.removeObserver(mapLifecycleObserver) context.unregisterComponentCallbacks(callbacks) } } DisposableEffect(mapView) { onDispose { mapView.onDestroy() mapView.removeAllViews() } } } private fun MapView.lifecycleObserver(previousState: MutableState<Lifecycle.Event>): LifecycleEventObserver = LifecycleEventObserver { _, event -> when (event) { Lifecycle.Event.ON_CREATE -> { if (previousState.value != Lifecycle.Event.ON_STOP) { this.onCreate(Bundle()) } } Lifecycle.Event.ON_RESUME -> this.onResume() Lifecycle.Event.ON_PAUSE -> this.onPause() else -> {} } previousState.value = event } private fun MapView.componentCallbacks(): ComponentCallbacks = object : ComponentCallbacks { override fun onConfigurationChanged(config: Configuration) {} override fun onLowMemory() { [email protected]() } } @Stable interface AMapState { /** * 地图视图 */ val mapView: MapView /** * 地图实例 */ val map: AMap } @Composable fun rememberAMapState(): AMapState { val context = LocalContext.current val isDarkTheme = isSystemInDarkTheme() return remember { AMapStateImpl(context, isDarkTheme) } } private class AMapStateImpl(context: Context, isDarkTheme: Boolean) : AMapState { override val mapView: MapView override val map: AMap init { MapsInitializer.updatePrivacyShow(context, true, true) MapsInitializer.updatePrivacyAgree(context, true) val options = AMapOptions().apply { // 设置logo位置 logoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT) // 不显示缩放控件 zoomControlsEnabled(false) // 设置地图类型 mapType(if (isDarkTheme) AMap.MAP_TYPE_NIGHT else AMap.MAP_TYPE_NORMAL) } mapView = MapView(context, options) map = mapView.map } }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/AMap.kt
4057145372
package top.chengdongqing.weui.feature.location.preview import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Navigation import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.amap.api.maps.CameraUpdateFactory import com.amap.api.maps.model.MarkerOptions import top.chengdongqing.weui.core.ui.components.R import top.chengdongqing.weui.core.ui.components.actionsheet.ActionSheetItem import top.chengdongqing.weui.core.ui.components.actionsheet.rememberActionSheetState import top.chengdongqing.weui.feature.location.AMap import top.chengdongqing.weui.feature.location.data.model.LocationPreviewItem import top.chengdongqing.weui.feature.location.data.model.MapType import top.chengdongqing.weui.feature.location.rememberAMapState import top.chengdongqing.weui.feature.location.utils.createBitmapDescriptor import top.chengdongqing.weui.feature.location.utils.navigateToLocation @Composable fun WeLocationPreview(location: LocationPreviewItem) { val context = LocalContext.current val state = rememberAMapState() val map = state.map LaunchedEffect(state) { // 设置地图视野 map.moveCamera(CameraUpdateFactory.newLatLngZoom(location.latLng, location.zoom)) // 添加定位标记 val marker = MarkerOptions().apply { position(location.latLng) icon( createBitmapDescriptor( context, R.drawable.ic_location_marker, 120, 120 ) ) } map.addMarker(marker) } Column(modifier = Modifier.fillMaxSize()) { AMap(modifier = Modifier.weight(1f), state) BottomBar(location) } } @Composable private fun BottomBar(location: LocationPreviewItem) { val actionSheet = rememberActionSheetState() val mapOptions = remember { listOf( ActionSheetItem("高德地图"), ActionSheetItem("百度地图"), ActionSheetItem("腾讯地图"), ActionSheetItem("谷歌地图"), ) } Row( modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.surface) .padding(horizontal = 20.dp, vertical = 40.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Column { Text( text = location.name, color = MaterialTheme.colorScheme.onPrimary, fontSize = 20.sp, fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.height(14.dp)) location.address?.let { Text( text = it, color = MaterialTheme.colorScheme.onSecondary, fontSize = 14.sp ) } } Column(horizontalAlignment = Alignment.CenterHorizontally) { val context = LocalContext.current Box( modifier = Modifier .size(40.dp) .clip(CircleShape) .background(MaterialTheme.colorScheme.background) .clickable { actionSheet.show(mapOptions) { index -> context.navigateToLocation( MapType.ofIndex(index)!!, location.latLng, location.name ) } }, contentAlignment = Alignment.Center ) { Icon( imageVector = Icons.Outlined.Navigation, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(24.dp) ) } Spacer(modifier = Modifier.height(4.dp)) Text(text = "导航", color = MaterialTheme.colorScheme.onSecondary, fontSize = 14.sp) } } }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/preview/LocationPreview.kt
1952413649
package top.chengdongqing.weui.feature.location.preview import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import top.chengdongqing.weui.core.ui.theme.WeUITheme import top.chengdongqing.weui.feature.location.data.model.LocationPreviewItem class LocationPreviewActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val location = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent.getParcelableExtra("location", LocationPreviewItem::class.java) } else { @Suppress("DEPRECATION") intent.getParcelableExtra("location") }!! setContent { WeUITheme { WeLocationPreview(location) } } } companion object { fun newIntent(context: Context) = Intent(context, LocationPreviewActivity::class.java) } } fun Context.previewLocation(location: LocationPreviewItem) { val intent = LocationPreviewActivity.newIntent(this).apply { putExtra("location", location) } startActivity(intent) }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/preview/LocationPreviewActivity.kt
466098523
package top.chengdongqing.weui.feature.location.data.repository import android.content.Context import androidx.datastore.preferences.core.edit import com.amap.api.maps.AMapUtils import com.amap.api.maps.model.LatLng import com.amap.api.services.core.AMapException import com.amap.api.services.core.PoiItemV2 import com.amap.api.services.geocoder.GeocodeResult import com.amap.api.services.geocoder.GeocodeSearch import com.amap.api.services.geocoder.RegeocodeAddress import com.amap.api.services.geocoder.RegeocodeQuery import com.amap.api.services.geocoder.RegeocodeResult import com.amap.api.services.poisearch.PoiResultV2 import com.amap.api.services.poisearch.PoiSearchV2 import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext import top.chengdongqing.weui.feature.location.data.model.LocationItem import top.chengdongqing.weui.feature.location.utils.toLatLng import top.chengdongqing.weui.feature.location.utils.toLatLonPoint import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine import kotlin.math.roundToInt class LocationRepositoryImpl(private val context: Context) : LocationRepository { override suspend fun locationToAddress(latLng: LatLng): RegeocodeAddress? = withContext(Dispatchers.IO) { suspendCoroutine { continuation -> val geocoderSearch = GeocodeSearch(context) geocoderSearch.setOnGeocodeSearchListener(object : GeocodeSearch.OnGeocodeSearchListener { override fun onRegeocodeSearched(result: RegeocodeResult?, resultCode: Int) { if (resultCode == AMapException.CODE_AMAP_SUCCESS) { continuation.resume(result?.regeocodeAddress) } else { continuation.resume(null) } } override fun onGeocodeSearched(geocodeResult: GeocodeResult?, rCode: Int) {} }) val query = RegeocodeQuery( latLng.toLatLonPoint(), 100_000f, GeocodeSearch.AMAP ) geocoderSearch.getFromLocationAsyn(query) } } override suspend fun search( location: LatLng?, keyword: String, pageNum: Int, pageSize: Int, current: LatLng? ): List<LocationItem> = withContext(Dispatchers.IO) { // 构建搜索参数:关键字,类别,区域 val query = PoiSearchV2.Query(keyword, "", "").apply { this.pageNum = pageNum this.pageSize = pageSize } val poiSearch = PoiSearchV2(context, query) // 限定搜索范围:坐标,半径 if (location != null) { poiSearch.bound = PoiSearchV2.SearchBound(location.toLatLonPoint(), 100_000) } suspendCoroutine { continuation -> poiSearch.setOnPoiSearchListener(object : PoiSearchV2.OnPoiSearchListener { override fun onPoiSearched(result: PoiResultV2?, resultCode: Int) { if (resultCode == AMapException.CODE_AMAP_SUCCESS && result?.query != null) { val items = result.pois.map { poiItem -> LocationItem( id = poiItem.poiId, name = poiItem.title, address = poiItem.adName, distance = if (current != null) { AMapUtils.calculateLineDistance( current, poiItem.latLonPoint.toLatLng() ).roundToInt() } else null, latLng = poiItem.latLonPoint.toLatLng() ) } continuation.resume(items) } else { continuation.resume(emptyList()) } } override fun onPoiItemSearched(poiItem: PoiItemV2?, rCode: Int) {} }) poiSearch.searchPOIAsyn() } } override val currentLocation: Flow<LatLng?> get() = context.locationDataStore.data .map { preferences -> val latitude = preferences[PreferencesKeys.LATITUDE] val longitude = preferences[PreferencesKeys.LONGITUDE] if (latitude != null && longitude != null) { LatLng(latitude, longitude) } else { null } } override suspend fun saveCurrentLocation(latLng: LatLng) { context.locationDataStore.edit { preferences -> preferences[PreferencesKeys.LATITUDE] = latLng.latitude preferences[PreferencesKeys.LONGITUDE] = latLng.longitude } } }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/data/repository/LocationRepositoryImpl.kt
431801724
package top.chengdongqing.weui.feature.location.data.repository import android.content.Context import androidx.datastore.preferences.core.doublePreferencesKey import androidx.datastore.preferences.preferencesDataStore val Context.locationDataStore by preferencesDataStore(name = "location") object PreferencesKeys { val LATITUDE = doublePreferencesKey("latitude") val LONGITUDE = doublePreferencesKey("longitude") }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/data/repository/LocationDataStore.kt
3452435093
package top.chengdongqing.weui.feature.location.data.repository import com.amap.api.maps.model.LatLng import com.amap.api.services.geocoder.RegeocodeAddress import kotlinx.coroutines.flow.Flow import top.chengdongqing.weui.feature.location.data.model.LocationItem interface LocationRepository { suspend fun locationToAddress(latLng: LatLng): RegeocodeAddress? suspend fun search( location: LatLng?, keyword: String, pageNum: Int, pageSize: Int, current: LatLng? ): List<LocationItem> val currentLocation: Flow<LatLng?> suspend fun saveCurrentLocation(latLng: LatLng) }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/data/repository/LocationRepository.kt
2499729512
package top.chengdongqing.weui.feature.location.data.model import android.os.Parcelable import com.amap.api.maps.model.LatLng import kotlinx.parcelize.Parcelize @Parcelize data class LocationItem( val id: String? = null, val name: String, val address: String? = null, val distance: Int? = null, val latLng: LatLng ) : Parcelable
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/data/model/LocationItem.kt
2848629460
package top.chengdongqing.weui.feature.location.data.model import android.os.Parcelable import com.amap.api.maps.model.LatLng import kotlinx.parcelize.Parcelize @Parcelize data class LocationPreviewItem( val latLng: LatLng, val name: String = "位置", val address: String? = null, val zoom: Float = 16f ) : Parcelable
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/data/model/LocationPreviewItem.kt
1800377301
package top.chengdongqing.weui.feature.location.data.model enum class MapType(val appName: String) { AMAP("高德"), BAIDU("百度"), TENCENT("腾讯"), GOOGLE("谷歌"); companion object { fun ofIndex(index: Int): MapType? { return entries.getOrNull(index) } } }
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/data/model/MapType.kt
409035319
package top.chengdongqing.weui.feature.network import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("top.chengdongqing.weui.feature.network.test", appContext.packageName) } }
WeUI/feature/network/src/androidTest/java/top/chengdongqing/weui/feature/network/ExampleInstrumentedTest.kt
726907869
package top.chengdongqing.weui.feature.network import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
WeUI/feature/network/src/test/java/top/chengdongqing/weui/feature/network/ExampleUnitTest.kt
2046744959
package top.chengdongqing.weui.feature.network.websocket import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem import top.chengdongqing.weui.core.ui.components.cardlist.cartList import top.chengdongqing.weui.core.ui.components.input.WeTextarea import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.components.toast.ToastIcon import top.chengdongqing.weui.core.ui.components.toast.rememberToastState @Composable fun WebSocketScreen(socketViewModel: WebSocketViewModel = viewModel()) { WeScreen(title = "WebSocket", description = "双向通信", scrollEnabled = false) { var connected by remember { mutableStateOf(false) } DisposableEffect(Unit) { onDispose { socketViewModel.close() } } if (!connected) { UnconnectedScreen(socketViewModel) { connected = it } } else { ConnectedScreen(socketViewModel) { connected = it } } } } @Composable private fun UnconnectedScreen( socketViewModel: WebSocketViewModel, setConnectState: (Boolean) -> Unit ) { var connecting by remember { mutableStateOf(false) } val toast = rememberToastState() WeButton( text = if (connecting) "连接中..." else "连接WebSocket", loading = connecting ) { connecting = true socketViewModel.open("wss://echo.websocket.org", onFailure = { toast.show("连接失败", ToastIcon.FAIL) connecting = false setConnectState(false) }) { toast.show("连接成功", ToastIcon.SUCCESS) setConnectState(true) } } } @Composable private fun ConnectedScreen( socketViewModel: WebSocketViewModel, setConnectState: (Boolean) -> Unit ) { val keyboardController = LocalSoftwareKeyboardController.current var text by remember { mutableStateOf("") } val toast = rememberToastState() WeTextarea(value = text, placeholder = "请输入内容") { text = it } Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "发送") { if (text.isNotBlank()) { socketViewModel.send(text) keyboardController?.hide() text = "" } else { toast.show("请输入内容", ToastIcon.FAIL) } } Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "断开连接", type = ButtonType.DANGER) { socketViewModel.close() setConnectState(false) } Spacer(modifier = Modifier.height(40.dp)) Text(text = "收到的消息", fontSize = 12.sp) Spacer(modifier = Modifier.height(10.dp)) LazyColumn(modifier = Modifier.cartList()) { itemsIndexed(socketViewModel.messages) { index, item -> WeCardListItem(label = "${index + 1}", value = item) } } }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/websocket/WebSocket.kt
4276150247
package top.chengdongqing.weui.feature.network.websocket import androidx.compose.runtime.mutableStateListOf import androidx.lifecycle.ViewModel import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okhttp3.WebSocket import okhttp3.WebSocketListener import top.chengdongqing.weui.core.utils.isTrue class WebSocketViewModel : ViewModel() { private var client: OkHttpClient? = null private var webSocket: WebSocket? = null val messages = mutableStateListOf<String>() fun open( url: String, onFailure: ((Throwable) -> Unit)? = null, onOpen: ((Response) -> Unit)? = null ) { val request = Request.Builder().url(url).build() val webSocketListener = TestWebSocketListener( onOpen = { onOpen?.invoke(it) }, onFailure = { onFailure?.invoke(it) } ) { messages.add(it) } client = OkHttpClient().apply { webSocket = newWebSocket(request, webSocketListener) } } fun send(message: String): Boolean { return webSocket?.send(message).isTrue() } fun close() { webSocket?.close(NORMAL_CLOSURE_STATUS, null) client?.dispatcher?.executorService?.shutdown() messages.clear() } } private const val NORMAL_CLOSURE_STATUS = 1000 private class TestWebSocketListener( val onOpen: (Response) -> Unit, val onFailure: (Throwable) -> Unit, val onMessage: (String) -> Unit ) : WebSocketListener() { override fun onOpen(webSocket: WebSocket, response: Response) { onOpen(response) } override fun onMessage(webSocket: WebSocket, text: String) { onMessage(text) } override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { t.printStackTrace() onFailure(t) } }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/websocket/WebSocketViewModel.kt
3799347505
package top.chengdongqing.weui.feature.network.navigation import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import top.chengdongqing.weui.feature.network.download.FileDownloadScreen import top.chengdongqing.weui.feature.network.request.HttpRequestScreen import top.chengdongqing.weui.feature.network.upload.FileUploadScreen import top.chengdongqing.weui.feature.network.websocket.WebSocketScreen fun NavGraphBuilder.addNetworkGraph() { composable("http_request") { HttpRequestScreen() } composable("file_upload") { FileUploadScreen() } composable("file_download") { FileDownloadScreen() } composable("web_socket") { WebSocketScreen() } }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/navigation/NetworkGraph.kt
3611544139
package top.chengdongqing.weui.feature.network.download.repository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.ResponseBody import top.chengdongqing.weui.feature.network.download.retrofit.DownloadService import top.chengdongqing.weui.feature.network.download.retrofit.RetrofitManger import java.io.IOException class DownloadRepositoryImpl : DownloadRepository { private val downloadService by lazy { RetrofitManger.retrofit.create(DownloadService::class.java) } override suspend fun downloadFile(filename: String): ResponseBody? { return withContext(Dispatchers.IO) { try { downloadService.downloadFile(filename) } catch (e: IOException) { null } } } }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/download/repository/DownloadRepositoryImpl.kt
1847294468
package top.chengdongqing.weui.feature.network.download.repository import okhttp3.ResponseBody interface DownloadRepository { suspend fun downloadFile(filename: String): ResponseBody? }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/download/repository/DownloadRepository.kt
2089654030
package top.chengdongqing.weui.feature.network.download.retrofit import okhttp3.ResponseBody import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Streaming interface DownloadService { @Streaming @GET("{filename}") suspend fun downloadFile(@Path("filename") filename: String): ResponseBody }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/download/retrofit/DownloadService.kt
1203405502
package top.chengdongqing.weui.feature.network.download.retrofit import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory internal object RetrofitManger { private const val BASE_URL = "https://s1.xiaomiev.com/activity-outer-assets/web/home/" val retrofit: Retrofit by lazy { Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() } }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/download/retrofit/RetrofitManger.kt
787762575
package top.chengdongqing.weui.feature.network.download import androidx.compose.foundation.Image import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.ImageBitmap import androidx.lifecycle.viewmodel.compose.viewModel import kotlinx.coroutines.launch import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.components.toast.ToastIcon import top.chengdongqing.weui.core.ui.components.toast.rememberToastState @Composable fun FileDownloadScreen(downloadViewModel: DownloadViewModel = viewModel()) { WeScreen(title = "FileDownload", description = "文件下载") { var bitmap by remember { mutableStateOf<ImageBitmap?>(null) } var downloading by remember { mutableStateOf(false) } val coroutineScope = rememberCoroutineScope() val toast = rememberToastState() bitmap?.let { Image(bitmap = it, contentDescription = null) } ?: WeButton( text = if (downloading) "下载中..." else "下载图片", loading = downloading ) { downloading = true coroutineScope.launch { bitmap = downloadViewModel.downloadFile("section1.jpg").also { if (it == null) { toast.show("下载失败", ToastIcon.FAIL) } } downloading = false } } } }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/download/FileDownload.kt
639498166
package top.chengdongqing.weui.feature.network.download import android.graphics.BitmapFactory import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.lifecycle.ViewModel import top.chengdongqing.weui.feature.network.download.repository.DownloadRepositoryImpl class DownloadViewModel : ViewModel() { private val downloadRepository by lazy { DownloadRepositoryImpl() } suspend fun downloadFile(filename: String): ImageBitmap? { return downloadRepository.downloadFile(filename)?.byteStream()?.use { BitmapFactory.decodeStream(it).asImageBitmap() } } }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/download/DownloadViewModel.kt
3213125138
package top.chengdongqing.weui.feature.network.request import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import com.google.gson.GsonBuilder import kotlinx.coroutines.launch import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.components.toast.ToastIcon import top.chengdongqing.weui.core.ui.components.toast.rememberToastState @Composable fun HttpRequestScreen(viewModel: CartViewModel = viewModel()) { WeScreen( title = "HttpRequest", description = "HTTP请求(OkHttp+Retrofit)", scrollEnabled = false ) { val toast = rememberToastState() val coroutineScope = rememberCoroutineScope() var content by remember { mutableStateOf<String?>(null) } var loading by remember { mutableStateOf(false) } WeButton( "查询推荐的商品", loading = loading, width = 200.dp, modifier = Modifier.align(Alignment.CenterHorizontally) ) { loading = true coroutineScope.launch { val res = viewModel.fetchRecommendProducts() loading = false if (res?.code == 200) { val gson = GsonBuilder().setPrettyPrinting().create() content = gson.toJson(res) } else { toast.show("请求失败", ToastIcon.FAIL) } } } content?.let { Spacer(modifier = Modifier.height(40.dp)) Box( modifier = Modifier .background( MaterialTheme.colorScheme.onBackground, RoundedCornerShape(6.dp) ) .padding(20.dp) .verticalScroll(rememberScrollState()) ) { Text( text = it, color = MaterialTheme.colorScheme.onPrimary, fontSize = 12.sp ) } } } }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/HttpRequest.kt
2926749040
package top.chengdongqing.weui.feature.network.request.retrofit import retrofit2.http.GET import retrofit2.http.Header import top.chengdongqing.weui.feature.network.request.data.model.RecommendItem import top.chengdongqing.weui.feature.network.request.data.model.Result interface CartService { @GET("rec/cartempty") suspend fun fetchRecommendProducts( @Header("Referer") referer: String = "https://www.mi.com" ): Result<List<RecommendItem>> }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/retrofit/CartService.kt
3609878434
package top.chengdongqing.weui.feature.network.request.retrofit import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory internal object RetrofitManger { private const val BASE_URL = "https://api2.order.mi.com/" val retrofit: Retrofit by lazy { Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() } }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/retrofit/RetrofitManger.kt
2540040301
package top.chengdongqing.weui.feature.network.request import androidx.lifecycle.ViewModel import top.chengdongqing.weui.feature.network.request.data.model.RecommendItem import top.chengdongqing.weui.feature.network.request.data.model.Result import top.chengdongqing.weui.feature.network.request.data.repository.CartRepositoryImpl class CartViewModel : ViewModel() { private val cartRepository by lazy { CartRepositoryImpl() } suspend fun fetchRecommendProducts(): Result<List<RecommendItem>>? { return cartRepository.fetchRecommendProducts() } }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/CartViewModel.kt
3023221031
package top.chengdongqing.weui.feature.network.request.data.repository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import top.chengdongqing.weui.feature.network.request.data.model.RecommendItem import top.chengdongqing.weui.feature.network.request.data.model.Result import top.chengdongqing.weui.feature.network.request.retrofit.CartService import top.chengdongqing.weui.feature.network.request.retrofit.RetrofitManger import java.io.IOException class CartRepositoryImpl : CartRepository { private val cartService by lazy { RetrofitManger.retrofit.create(CartService::class.java) } override suspend fun fetchRecommendProducts(): Result<List<RecommendItem>>? { return withContext(Dispatchers.IO) { try { cartService.fetchRecommendProducts() } catch (e: IOException) { null } } } }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/data/repository/CartRepositoryImpl.kt
317352688
package top.chengdongqing.weui.feature.network.request.data.repository import top.chengdongqing.weui.feature.network.request.data.model.RecommendItem import top.chengdongqing.weui.feature.network.request.data.model.Result interface CartRepository { suspend fun fetchRecommendProducts(): Result<List<RecommendItem>>? }
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/data/repository/CartRepository.kt
254195160
package top.chengdongqing.weui.feature.network.request.data.model data class Result<out T>( val code: Int, val msg: String? = null, val data: T? = null )
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/data/model/Result.kt
2520023981