Improve Android widget binding and launcher interactions
This commit is contained in:
1 parent
bf424102c8
commit
274b8538b7
8 files changed
+143
-43
No files matched your search
+2
-2
@@ -50,9 +50,9 @@ $env:LAUNCHER_DEVICE_TOKEN = '<设备令牌>'
|
||||
|
||||
内置值只在新安装(没有本机连接设置)时生效;用户手动保存过的配置优先,清空两项并保存仍可关闭同步。
|
||||
|
||||
同步设置页的「测试第三方小组件」是 Debug 排障入口:枚举设备上已安装的 AppWidget Provider,点「绑定」拉起系统授权弹窗,授权成功后在页面内预览真实组件并回显绑定状态。普通 Launcher 页面仍按布局里的 `widget` 元素渲染,点击桌面上的组件占位块可发起系统授权。同一 provider 可以绑定到多个实例,已绑定实例会随应用重启恢复。
|
||||
同步设置页的「测试第三方小组件」是 Debug 排障入口:枚举设备上已安装的 AppWidget Provider,点「绑定」拉起系统授权弹窗,授权成功后在页面内预览真实组件并回显绑定状态。普通 Launcher 页面仍按布局里的 `widget` 元素渲染,桌面回到前台或收到新布局时,会自动尝试绑定已获系统许可且无需强制配置的组件。仍需授权或配置时,点击组件占位块继续。同一 provider 可以绑定到多个实例,已绑定实例会随应用重启恢复。
|
||||
|
||||
用系统应用列表打开「布局同步」,或在 Vibe Launcher 的桌面空白处长按。填写服务根地址和设备令牌,点「保存并同步」,然后回到桌面。测试时可以调整任意一个现有图标的位置,发布后确认手机的位置和版本号都更新。桌面处于前台时每分钟查询一次,回到桌面时立即查询。清空两项连接设置并保存可以关闭同步,已应用的布局仍可离线使用。
|
||||
用系统应用列表打开「布局同步」。填写服务根地址和设备令牌,点「保存并同步」,然后回到桌面。测试时可以调整任意一个现有图标的位置,发布后确认手机的位置和版本号都更新。桌面处于前台时每分钟查询一次,回到桌面时立即查询。清空两项连接设置并保存可以关闭同步,已应用的布局仍可离线使用。
|
||||
|
||||
| 环境 | Android 中填写的服务根地址 |
|
||||
| --- | --- |
|
||||
|
||||
@@ -28,7 +28,8 @@
|
||||
<activity
|
||||
android:name=".SyncSettingsActivity"
|
||||
android:exported="true"
|
||||
android:label="布局同步">
|
||||
android:label="布局同步"
|
||||
android:taskAffinity="${applicationId}.sync">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.ttstd.compose.launcher
|
||||
|
||||
import android.app.Application
|
||||
import android.graphics.Bitmap
|
||||
import android.widget.Toast
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.ttstd.compose.launcher.core.AppLaunch
|
||||
@@ -77,20 +78,24 @@ class LauncherViewModel(app: Application) : AndroidViewModel(app) {
|
||||
|
||||
fun onItemClick(def: ItemDef) {
|
||||
val ctx = getApplication<Application>()
|
||||
when (def.type) {
|
||||
val opened = when (def.type) {
|
||||
"app_icon" -> AppLaunch.launchPackage(ctx, def.payload.pkg.orEmpty())
|
||||
"shortcut" -> {
|
||||
val target = def.payload.intent?.takeIf { it.isNotBlank() }
|
||||
?: def.payload.pkg.orEmpty()
|
||||
AppLaunch.launchUriOrAction(ctx, target)
|
||||
}
|
||||
else -> Unit
|
||||
else -> return
|
||||
}
|
||||
if (!opened) Toast.makeText(ctx, "找不到应用或无法启动", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
|
||||
fun onItemLongClick(def: ItemDef) {
|
||||
val pkg = def.payload.pkg ?: return
|
||||
AppLaunch.openAppInfo(getApplication(), pkg)
|
||||
val ctx = getApplication<Application>()
|
||||
if (!AppLaunch.openAppInfo(ctx, pkg)) {
|
||||
Toast.makeText(ctx, "找不到应用或无法打开应用详情", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
|
||||
fun onPageChanged(index: Int) {
|
||||
|
||||
@@ -12,7 +12,6 @@ import androidx.activity.OnBackPressedCallback
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
@@ -26,7 +25,6 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
@@ -38,6 +36,7 @@ import com.ttstd.compose.launcher.ui.theme.VibeLauncherTheme
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
|
||||
/* =============================================================================
|
||||
* Launcher 入口
|
||||
@@ -92,11 +91,7 @@ class MainActivity : ComponentActivity() {
|
||||
val wallpaper by vm.wallpaper.collectAsState()
|
||||
val degraded by vm.degraded.collectAsState()
|
||||
|
||||
Box(Modifier.fillMaxSize().pointerInput(Unit) {
|
||||
detectTapGestures(onLongPress = {
|
||||
startActivity(Intent(this@MainActivity, SyncSettingsActivity::class.java))
|
||||
})
|
||||
}) {
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
LauncherCanvas(
|
||||
layout = layout,
|
||||
icons = vm.icons,
|
||||
@@ -145,6 +140,21 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.RESUMED) {
|
||||
(application as LauncherApp).graph.repo.layout.collectLatest { layout ->
|
||||
if (layout == null) return@collectLatest
|
||||
try {
|
||||
widgets.bindAvailable(layout)
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: RuntimeException) {
|
||||
Log.w(TAG, "Automatic widget binding failed: ${error.javaClass.simpleName}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 首帧埋点:onPreDraw 比 onResume 准,它是"即将真正绘制"的时刻
|
||||
window.decorView.viewTreeObserver.addOnPreDrawListener(
|
||||
object : ViewTreeObserver.OnPreDrawListener {
|
||||
|
||||
@@ -2,7 +2,9 @@ package com.ttstd.compose.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
@@ -43,20 +45,37 @@ object AppLaunch {
|
||||
return start(context, intent)
|
||||
}
|
||||
|
||||
private fun start(context: Context, intent: Intent): Boolean = runCatching {
|
||||
context.startActivity(intent)
|
||||
private fun start(context: Context, intent: Intent): Boolean {
|
||||
// Some Settings builds crash after accepting an app-info intent for a missing package.
|
||||
if (intent.action == Settings.ACTION_APPLICATION_DETAILS_SETTINGS) {
|
||||
val pkg = intent.data?.takeIf { it.scheme == "package" }?.schemeSpecificPart
|
||||
if (pkg.isNullOrBlank() || !isInstalled(context, pkg)) return false
|
||||
}
|
||||
return runCatching {
|
||||
context.startActivity(intent)
|
||||
true
|
||||
}.getOrElse {
|
||||
Log.w(TAG, "start failed: ${it.message}")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun isInstalled(context: Context, pkg: String): Boolean = try {
|
||||
@Suppress("DEPRECATION")
|
||||
context.packageManager.getApplicationInfo(pkg, 0)
|
||||
true
|
||||
}.getOrElse {
|
||||
Log.w(TAG, "start failed: ${it.message}")
|
||||
} catch (_: PackageManager.NameNotFoundException) {
|
||||
false
|
||||
} catch (_: SecurityException) {
|
||||
false
|
||||
}
|
||||
|
||||
/** 长按图标 → 应用详情(卸载/强制停止)。桌面必备,否则用户装了就卸不掉 */
|
||||
fun openAppInfo(context: Context, pkg: String) {
|
||||
fun openAppInfo(context: Context, pkg: String): Boolean {
|
||||
val intent = Intent(
|
||||
android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||
Uri.fromParts("package", pkg, null),
|
||||
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
return start(context, intent)
|
||||
}
|
||||
}
|
||||
+38
-4
@@ -8,9 +8,11 @@ import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Process
|
||||
import android.view.View
|
||||
import kotlinx.coroutines.yield
|
||||
|
||||
class AppWidgetHostController(
|
||||
private val context: Context,
|
||||
@@ -23,6 +25,32 @@ class AppWidgetHostController(
|
||||
private val bindings = context.getSharedPreferences("widget_bindings", Context.MODE_PRIVATE)
|
||||
private val bindingChanges = mutableIntStateOf(0)
|
||||
|
||||
// Run from the resumed Activity on the main thread, alongside manual binding and view creation.
|
||||
suspend fun bindAvailable(layout: LauncherLayout) {
|
||||
val installed by lazy { manager.installedProviders.associateBy { it.provider } }
|
||||
for (page in layout.pages) {
|
||||
for (item in page.items) {
|
||||
if (item.type != "widget") continue
|
||||
val provider = item.payload.provider?.let(ComponentName::unflattenFromString) ?: continue
|
||||
yield()
|
||||
if (pending != null) return
|
||||
val info = installed[provider] ?: continue
|
||||
val key = widgetBindingKey(page.index, item.id)
|
||||
if (info.requiresConfiguration() || boundId(key, info) != null) continue
|
||||
val id = host.allocateAppWidgetId()
|
||||
var retained = false
|
||||
try {
|
||||
if (manager.bindAppWidgetIdIfAllowed(id, provider)) {
|
||||
saveBinding(key, id)
|
||||
retained = true
|
||||
}
|
||||
} finally {
|
||||
if (!retained) host.deleteAppWidgetId(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun requestBind(key: String, provider: String, launch: (Intent) -> Unit, configure: (Int) -> Unit) {
|
||||
val info = resolveProvider(provider) ?: return
|
||||
if (pending != null || boundId(key, info) != null) return
|
||||
@@ -67,9 +95,7 @@ class AppWidgetHostController(
|
||||
finishBinding(false)
|
||||
return
|
||||
}
|
||||
val optional = android.os.Build.VERSION.SDK_INT >= 31 &&
|
||||
info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_CONFIGURATION_OPTIONAL != 0
|
||||
if (info.configure == null || optional) {
|
||||
if (!info.requiresConfiguration()) {
|
||||
finishBinding(true)
|
||||
return
|
||||
}
|
||||
@@ -90,13 +116,21 @@ class AppWidgetHostController(
|
||||
pending = null
|
||||
val provider = ComponentName.unflattenFromString(request.provider)
|
||||
if (accepted && manager.getAppWidgetInfo(request.id)?.provider == provider) {
|
||||
bindings.edit().putInt(request.key, request.id).apply()
|
||||
saveBinding(request.key, request.id)
|
||||
} else {
|
||||
host.deleteAppWidgetId(request.id)
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveBinding(key: String, id: Int) {
|
||||
bindings.edit().putInt(key, id).apply()
|
||||
bindingChanges.intValue++
|
||||
}
|
||||
|
||||
private fun AppWidgetProviderInfo.requiresConfiguration(): Boolean =
|
||||
configure != null && (Build.VERSION.SDK_INT < 31 ||
|
||||
widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_CONFIGURATION_OPTIONAL == 0)
|
||||
|
||||
private fun boundId(key: String, info: AppWidgetProviderInfo): Int? {
|
||||
val id = bindings.getInt(key, -1)
|
||||
if (id < 0) return null
|
||||
|
||||
@@ -12,3 +12,5 @@ import android.view.View
|
||||
interface WidgetHostProvider {
|
||||
fun obtain(key: String, provider: String, widthDp: Int, heightDp: Int): View?
|
||||
}
|
||||
|
||||
internal fun widgetBindingKey(pageIndex: Int, itemId: String) = "$pageIndex:$itemId"
|
||||
@@ -7,6 +7,8 @@ import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
@@ -29,6 +31,10 @@ 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.draw.drawBehind
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
@@ -37,6 +43,7 @@ import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
@@ -50,6 +57,7 @@ import com.ttstd.compose.launcher.core.LauncherLayout
|
||||
import com.ttstd.compose.launcher.core.PageDef
|
||||
import com.ttstd.compose.launcher.core.PlacedItem
|
||||
import com.ttstd.compose.launcher.core.WidgetHostProvider
|
||||
import com.ttstd.compose.launcher.core.widgetBindingKey
|
||||
import com.ttstd.compose.launcher.core.avoidSystemInsets
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@@ -213,7 +221,7 @@ private fun CanvasPage(
|
||||
) {
|
||||
CanvasItemView(
|
||||
def = def,
|
||||
widgetKey = "${page.index}:${def.id}",
|
||||
widgetKey = widgetBindingKey(page.index, def.id),
|
||||
placed = p,
|
||||
icons = icons,
|
||||
widgetHost = widgetHost,
|
||||
@@ -305,6 +313,33 @@ private fun CanvasItemView(
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun iconPressModifier(iconSize: Dp, onClick: () -> Unit, onLongClick: () -> Unit): Modifier {
|
||||
val interactions = remember { MutableInteractionSource() }
|
||||
val pressed = interactions.collectIsPressedAsState()
|
||||
return Modifier
|
||||
.fillMaxSize()
|
||||
.drawBehind {
|
||||
if (pressed.value) {
|
||||
val icon = iconSize.toPx()
|
||||
val square = maxOf(size.width + icon * 0.18f, size.height + icon * 0.28f)
|
||||
drawRoundRect(
|
||||
color = Color.White.copy(alpha = 0.15f),
|
||||
topLeft = Offset((size.width - square) / 2f, (size.height - square) / 2f - icon * 0.09f),
|
||||
size = Size(square, square),
|
||||
cornerRadius = CornerRadius(square * 0.20f),
|
||||
)
|
||||
}
|
||||
}
|
||||
.combinedClickable(
|
||||
interactionSource = interactions,
|
||||
indication = null,
|
||||
onClick = onClick,
|
||||
onLongClick = onLongClick,
|
||||
)
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun AppIconView(
|
||||
@@ -322,15 +357,12 @@ private fun AppIconView(
|
||||
value = icons.load(pkg, sizePx)
|
||||
}
|
||||
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.combinedClickable(
|
||||
onClick = onClick,
|
||||
onLongClick = onLongClick,
|
||||
),
|
||||
) {
|
||||
val side = with(density) { sizePx.toDp() }
|
||||
val side = with(density) { sizePx.toDp() }
|
||||
Box(
|
||||
modifier = iconPressModifier(side, onClick, onLongClick),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
val shape = RoundedCornerShape(side * 0.24f)
|
||||
if (bmp != null) {
|
||||
Image(
|
||||
@@ -383,15 +415,12 @@ private fun ShortcutView(
|
||||
onLongClick: () -> Unit,
|
||||
) {
|
||||
val density = LocalDensity.current
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.combinedClickable(
|
||||
onClick = onClick,
|
||||
onLongClick = onLongClick,
|
||||
),
|
||||
) {
|
||||
val side = with(density) { sizePx.toDp() }
|
||||
val side = with(density) { sizePx.toDp() }
|
||||
Box(
|
||||
modifier = iconPressModifier(side, onClick, onLongClick),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(side)
|
||||
|
||||
Reference in new issue
Block a user