Jetpack 之Glance+Compose实现一个小组件

2024-02-20 01:20

本文主要是介绍Jetpack 之Glance+Compose实现一个小组件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Glance,官方对其解释是使用 Jetpack Compose 样式的 API 构建远程 Surface 的布局,通俗的讲就是使用Compose风格的API来搭建小插件布局,其最新版本是2022年2月23日更新的1.0.0-alpha03。众所周知,Compose样式的API与原生差别不小,至于widget这块改动如何,接下来让我们来一探究竟。

声明依赖项

第一步肯定要添加对应依赖,相应的都是在build.gradle中添加,如果你的工程还没支持Compose,要先添加:

android {buildFeatures {compose = true}composeOptions {kotlinCompilerExtensionVersion = "1.1.0-beta03"}kotlinOptions {jvmTarget = "1.8"}
}

如果已经支持,上述依赖可以省略,但下述依赖不能省略,继续添加:

dependencies {implementation("androidx.glance:glance-appwidget:1.0.0-alpha03")implementation("androidx.glance:glance-wear-tiles:1.0.0-alpha03")
}

以上是官方的标准依赖方式,同样以下面这种方式依赖也可以:

implementation 'androidx.glance:glance-appwidget:+'
implementation 'androidx.glance:glance:+'
implementation "androidx.glance:glance-appwidget:1.0.0-alpha03"

创建对应 widget

首先编写对应布局,放在对应/layout/xml目录下:

widget_info.xml

<?xml version="1.0" encoding="utf-8"?>
<appwidget-providerxmlns:android="http://schemas.android.com/apk/res/android"android:description="@string/app_name"android:minWidth="150dp"android:minHeight="66dp"android:resizeMode="horizontal|vertical"android:targetCellWidth="3"android:targetCellHeight="2"android:widgetCategory="home_screen"/>

我在上一篇介绍widget的文章中说过,widget其实就是个广播,广播属于四大组件,而四大组件都要在AndroidManifest清单文件中注册:

<receiverandroid:name=".CounterWidgetReceiver"android:enabled="@bool/glance_appwidget_available"android:exported="false"><intent-filter><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter><meta-dataandroid:name="android.appwidget.provider"android:resource="@xml/widget_info" />
</receiver>

对应CounterWidgetReceiver代码为:

import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
import com.ktfly.comapp.ui.theme.CounterWidgetclass CounterWidgetReceiver : GlanceAppWidgetReceiver(){override val glanceAppWidget: GlanceAppWidget = CounterWidget()
}

可能看到这里你就迷惑了,widget对应广播类不是要继承AppWidgetProvider然后实现相应方法的吗,其实Glance提供的GlanceAppWidgetReceiver类就已经继承了AppWidgetProvider,我们使用Glance需要GlanceAppWidgetReceiver:

abstract class GlanceAppWidgetReceiver : AppWidgetProvider() {private companion object {private const val TAG = "GlanceAppWidgetReceiver"}/*** Instance of the [GlanceAppWidget] to use to generate the App Widget and send it to the* [AppWidgetManager]*/abstract val glanceAppWidget: GlanceAppWidget@CallSuperoverride fun onUpdate(context: Context,appWidgetManager: AppWidgetManager,appWidgetIds: IntArray) {if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {Log.w(TAG,"Using Glance in devices with API<23 is untested and might behave unexpectedly.")}goAsync {updateManager(context)appWidgetIds.map { async { glanceAppWidget.update(context, appWidgetManager, it) } }.awaitAll()}}@CallSuperoverride fun onAppWidgetOptionsChanged(context: Context,appWidgetManager: AppWidgetManager,appWidgetId: Int,newOptions: Bundle) {goAsync {updateManager(context)glanceAppWidget.resize(context, appWidgetManager, appWidgetId, newOptions)}}@CallSuperoverride fun onDeleted(context: Context, appWidgetIds: IntArray) {goAsync {updateManager(context)appWidgetIds.forEach { glanceAppWidget.deleted(context, it) }}}private fun CoroutineScope.updateManager(context: Context) {launch {runAndLogExceptions {GlanceAppWidgetManager(context).updateReceiver(this@GlanceAppWidgetReceiver, glanceAppWidget)}}}override fun onReceive(context: Context, intent: Intent) {runAndLogExceptions {if (intent.action == Intent.ACTION_LOCALE_CHANGED) {val appWidgetManager = AppWidgetManager.getInstance(context)val componentName =ComponentName(context.packageName, checkNotNull(javaClass.canonicalName))onUpdate(context,appWidgetManager,appWidgetManager.getAppWidgetIds(componentName))return}super.onReceive(context, intent)}}
}private inline fun runAndLogExceptions(block: () -> Unit) {try {block()} catch (ex: CancellationException) {// Nothing to do} catch (throwable: Throwable) {logException(throwable)}
}

基本流程方法跟原生widget的差别不大,其含义也无差别,如果对原生Widget不太了解的同学可以翻阅我上一篇文章,这里还有官方注释:“Using Glance in devices with API<23 is untested and might behave unexpectedly.”。在6.0版本以下的Android系统上使用Glance的情况未经测试可能有出乎意料的情况发生。在开始编写widget代码之前,我们先来了解下其使用组件与Compose中的对应组件的些许差别。

差别

根据官方提示,可使用的Compose组合项如下:Box、Row、Column、Text、Button、LazyColumn、Image、Spacer。原生widget是不支持自定义View的,但Compose能通过自定义组件的方式来“自定义”出我们想要的视图,这一点来看相对更加灵活。

Compose中使用的修饰符是Modifier,这里修饰可组合项的修饰符是GlanceModifier,使用方式并无二致,其余组件也有些许差异,这个我们放到后面来说,

Action

以前使用widget跳转页面啥的,都离不开PendingIntent,但是Glance中则采取另一套方式:

actionStartActivity

看函数命名就得知,通过Action启动Activity。共有三种使用方式:

// 通过包名启动Activity
public fun actionStartActivity(componentName: ComponentName,parameters: ActionParameters = actionParametersOf()
): Action = StartActivityComponentAction(componentName, parameters)// 直接启动Activity
public fun <T : Activity> actionStartActivity(activity: Class<T>,parameters: ActionParameters = actionParametersOf()
): Action = StartActivityClassAction(activity, parameters)//调用actionStartActivity启动Activity,内联函数
public inline fun <reified T : Activity> actionStartActivity(parameters: ActionParameters = actionParametersOf()
): Action = actionStartActivity(T::class.java, parameters)\

其对应的使用方式也简单:

Button(text = "Jump", onClick = actionStartActivity(ComponentName("com.ktfly.comapp","com.ktfly.comapp.page.ShowActivity")))
Button(text = "Jump", onClick = actionStartActivity<ShowActivity>())
Button(text = "Jump", onClick = actionStartActivity(ShowActivity::class.java))

actionRunCallback

顾名思义,此函数是通过Action执行Callback,以下是官方提供的使用说明:\

fun <T : ActionCallback> actionRunCallback(callbackClass: Class<T>, parameters: ActionParameters = actionParametersOf()
): Actioninline fun <reified T : ActionCallback> actionRunCallback(parameters: ActionParameters = actionParametersOf()): Action

使用方式:

先创建一个继承actionRunCallback的回调类:

class ActionDemoCallBack : ActionCallback {override suspend fun onRun(context: Context, glanceId: GlanceId, parameters: ActionParameters) {TODO("Not yet implemented")}
}

然后在控件中调用:

Button(text = "CallBack", onClick = actionRunCallback<ActionDemoCallBack>())Button(text = "CallBack", onClick = actionRunCallback(ActionDemoCallBack::class.java))\

actionStartService

此函数是通过Action启动Service,有以下四个使用方式:

fun actionStartService(intent: Intent, isForegroundService: Boolean = false
): Actionfun actionStartService(componentName: ComponentName, isForegroundService: Boolean = false
): Actionfun <T : Service> actionStartService(service: Class<T>, isForegroundService: Boolean = false
): Actioninline fun <reified T : Service> actionStartService(isForegroundService: Boolean = false): Action

这里的isForegroundService参数含义是此服务是前台服务。在调用之前也需要先创建对应Service:

class ActionDemoService : Service() {override fun onBind(intent: Intent?): IBinder? {TODO("Not yet implemented")}
}

其在控件中使用方式如下:

Button(text = "start", onClick = actionStartService<ActionDemoService>())Button(text = "start", onClick = actionStartService(ActionDemoService::class.java))

actionStartBroadcastReceiver

此函数是通过Action启动BroadcastReceiver,有以下使用方式:

fun actionSendBroadcast(action: String, componentName: ComponentName? = null
): Actionfun actionSendBroadcast(intent: Intent): Actionfun actionSendBroadcast(componentName: ComponentName): Actionfun <T : BroadcastReceiver> actionSendBroadcast(receiver: Class<T>): Actioninline fun <reified T : BroadcastReceiver> actionSendBroadcast(): Actionfun actionStartActivity(intent: Intent, parameters: ActionParameters = actionParametersOf()
): Action

其各函数用法跟actionStartActivity函数差不多,这里不做赘述。你会发现以上函数中经常出现ActionParameters。其实ActionParameters就是给Action提供参数,这里不做赘述。

创建widget

创建对应的widget类,通过GlanceStateDefinition来保留GlanceAppWidget的状态,通过点击事件回调自定义的ActionCallBack达到更改widget中数字的目的:

import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.glance.*
import androidx.glance.action.ActionParameters
import androidx.glance.action.actionParametersOf
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.action.ActionCallback
import androidx.glance.appwidget.action.actionRunCallback
import androidx.glance.appwidget.state.updateAppWidgetState
import androidx.glance.layout.*
import androidx.glance.state.GlanceStateDefinition
import androidx.glance.state.PreferencesGlanceStateDefinition
import androidx.glance.text.Text
import androidx.glance.text.TextAlign
import androidx.glance.text.TextStyle
import androidx.glance.unit.ColorProviderprivate val countPreferenceKey = intPreferencesKey("widget-key")
private val countParamKey = ActionParameters.Key<Int>("widget-key")class CounterWidget : GlanceAppWidget(){override val stateDefinition: GlanceStateDefinition<*> =PreferencesGlanceStateDefinition@Composableoverride fun Content(){val prefs = currentState<Preferences>()val count = prefs[countPreferenceKey] ?: 1Column(horizontalAlignment = Alignment.CenterHorizontally,verticalAlignment = Alignment.CenterVertically,modifier = GlanceModifier.background(Color.Yellow).fillMaxSize()) {Text(text = count.toString(),modifier = GlanceModifier.fillMaxWidth(),style = TextStyle(textAlign = TextAlign.Center,color = ColorProvider(Color.Blue),fontSize = 50.sp))Spacer(modifier = GlanceModifier.padding(8.dp))Button(text = "变两倍",modifier = GlanceModifier.background(Color(0xFFB6C0C9)).size(100.dp,50.dp),onClick = actionRunCallback<UpdateActionCallback>(parameters = actionParametersOf(countParamKey to (count + count))))}}
}class UpdateActionCallback : ActionCallback{override suspend fun onRun(context: Context, glanceId: GlanceId,parameters: ActionParameters) {val count = requireNotNull(parameters[countParamKey])updateAppWidgetState(context = context,definition = PreferencesGlanceStateDefinition,glanceId = glanceId){ preferences ->preferences.toMutablePreferences().apply {this[countPreferenceKey] = count}}CounterWidget().update(context,glanceId)}
}

运行后效果如下:

Glance- Widget.gif

也许你会发现上述导包与平常Compose导包不一样:

image.gif

控件导的包都是glance包下的,当然不仅是Column,还有Button、Image等参数都有变化,但变化不大,例如Image的差异:

原Compose中:
Image(modifier = modifier,painter = BitmapPainter(bitmap),contentDescription = "",contentScale = contentScale)Image(modifier = modifier,painter = painterResource(资源id),contentDescription = "",contentScale = contentScale)Glance中:
public fun Image(provider: ImageProvider,contentDescription: String?,modifier: GlanceModifier = GlanceModifier,contentScale: ContentScale = ContentScale.Fit
)

其余控件差异大同小异,这里不做赘述。

这篇关于Jetpack 之Glance+Compose实现一个小组件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/726605

相关文章

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

利用python实现对excel文件进行加密

《利用python实现对excel文件进行加密》由于文件内容的私密性,需要对Excel文件进行加密,保护文件以免给第三方看到,本文将以Python语言为例,和大家讲讲如何对Excel文件进行加密,感兴... 目录前言方法一:使用pywin32库(仅限Windows)方法二:使用msoffcrypto-too