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

相关文章

C#高效实现在Word文档中自动化创建图表的可视化方案

《C#高效实现在Word文档中自动化创建图表的可视化方案》本文将深入探讨如何利用C#,结合一款功能强大的第三方库,实现在Word文档中自动化创建图表,为你的数据呈现和报告生成提供一套实用且高效的解决方... 目录Word文档图表自动化:为什么选择C#?从零开始:C#实现Word文档图表的基本步骤深度优化:C

nginx跨域访问配置的几种方法实现

《nginx跨域访问配置的几种方法实现》本文详细介绍了Nginx跨域配置方法,包括基本配置、只允许指定域名、携带Cookie的跨域、动态设置允许的Origin、支持不同路径的跨域控制、静态资源跨域以及... 目录一、基本跨域配置二、只允许指定域名跨域三、完整示例四、配置后重载 nginx五、注意事项六、支持

Qt实现对Word网页的读取功能

《Qt实现对Word网页的读取功能》文章介绍了几种在Qt中实现Word文档(.docx/.doc)读写功能的方法,包括基于QAxObject的COM接口调用、DOCX模板替换及跨平台解决方案,重点讨论... 目录1. 核心实现方式2. 基于QAxObject的COM接口调用(Windows专用)2.1 环境

MySQL查看表的历史SQL的几种实现方法

《MySQL查看表的历史SQL的几种实现方法》:本文主要介绍多种查看MySQL表历史SQL的方法,包括通用查询日志、慢查询日志、performance_schema、binlog、第三方工具等,并... 目录mysql 查看某张表的历史SQL1.查看MySQL通用查询日志(需提前开启)2.查看慢查询日志3.

Java实现字符串大小写转换的常用方法

《Java实现字符串大小写转换的常用方法》在Java中,字符串大小写转换是文本处理的核心操作之一,Java提供了多种灵活的方式来实现大小写转换,适用于不同场景和需求,本文将全面解析大小写转换的各种方法... 目录前言核心转换方法1.String类的基础方法2. 考虑区域设置的转换3. 字符级别的转换高级转换

使用Python实现局域网远程监控电脑屏幕的方法

《使用Python实现局域网远程监控电脑屏幕的方法》文章介绍了两种使用Python在局域网内实现远程监控电脑屏幕的方法,方法一使用mss和socket,方法二使用PyAutoGUI和Flask,每种方... 目录方法一:使用mss和socket实现屏幕共享服务端(被监控端)客户端(监控端)方法二:使用PyA

MyBatis-Plus逻辑删除实现过程

《MyBatis-Plus逻辑删除实现过程》本文介绍了MyBatis-Plus如何实现逻辑删除功能,包括自动填充字段、配置与实现步骤、常见应用场景,并展示了如何使用remove方法进行逻辑删除,逻辑删... 目录1. 逻辑删除的必要性编程1.1 逻辑删除的定义1.2 逻辑删php除的优点1.3 适用场景2.

C#借助Spire.XLS for .NET实现在Excel中添加文档属性

《C#借助Spire.XLSfor.NET实现在Excel中添加文档属性》在日常的数据处理和项目管理中,Excel文档扮演着举足轻重的角色,本文将深入探讨如何在C#中借助强大的第三方库Spire.... 目录为什么需要程序化添加Excel文档属性使用Spire.XLS for .NET库实现文档属性管理Sp

Python+FFmpeg实现视频自动化处理的完整指南

《Python+FFmpeg实现视频自动化处理的完整指南》本文总结了一套在Python中使用subprocess.run调用FFmpeg进行视频自动化处理的解决方案,涵盖了跨平台硬件加速、中间素材处理... 目录一、 跨平台硬件加速:统一接口设计1. 核心映射逻辑2. python 实现代码二、 中间素材处

Java数组动态扩容的实现示例

《Java数组动态扩容的实现示例》本文主要介绍了Java数组动态扩容的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1 问题2 方法3 结语1 问题实现动态的给数组添加元素效果,实现对数组扩容,原始数组使用静态分配