Android 桌面小组件使用

基本步骤

1.创建小组件布局

这里需要注意的事,小组件布局里不能使用自定义View,只能使用原生的组件,比如说LinearLayout,TextView,连约束布局都不能使用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="@color/white"android:orientation="vertical"android:padding="16dp"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:id="@+id/tvDate"style="@style/textStyle14"android:textColor="#313131"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="2023-12-10" /><ImageViewandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1" /><TextViewandroid:id="@+id/tvTime"android:textColor="#313131"style="@style/textStyle14"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="12:10" /></LinearLayout><LinearLayoutandroid:layout_marginTop="16dp"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><ImageViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/result_clean"/><LinearLayoutandroid:orientation="vertical"android:layout_width="0dp"android:layout_marginStart="9dp"android:gravity="center_vertical"android:layout_height="match_parent"android:layout_weight="1" ><TextViewstyle="@style/textStyle14"android:textColor="#313131"android:textStyle="bold"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="125.4MB"/><TextViewstyle="@style/textStyle14"android:textColor="#313131"android:textStyle="bold"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Junk"/></LinearLayout><TextViewandroid:layout_gravity="center_vertical"android:id="@+id/tvClean"android:textColor="#313131"style="@style/textStyle14"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Clean" /></LinearLayout></LinearLayout>

2.创建provider

import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.widget.RemoteViews
import android.widget.RemoteViews.RemoteView
import ten.jou.recover.Rclass CleaningWidget : AppWidgetProvider() {override fun onUpdate(context: Context,appWidgetManager: AppWidgetManager,appWidgetIds: IntArray) {appWidgetIds.forEach {//如果小组件布局中使用不支持的组件,这里创建RemoteViews时候,IDE会报红提示!val remoteView = RemoteViews(context.packageName, R.layout.widget_layout)//绑定数据remoteView.setTextViewText(R.id.tv1,"hello world")appWidgetManager.updateAppWidget(it, remoteView)}}
}

AppWidgetProvider本质就是一个广播接收器,所以在清单文件需要声明(见步骤4)

这里先补充下,RemoteViews对于TextView,ImageView等View,有设置文本,字体颜色,图片等相关方法,但并不是所有方法都支持,绑定数据的时候需要注意下小组件是否支持!

3.创建xml属性声明

在xml文件夹里新建widget_info.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:targetCellWidth="4"android:targetCellHeight="2"android:minWidth="250dp"android:minHeight="110dp"android:updatePeriodMillis="0"android:initialLayout="@layout/widget_layout"tools:targetApi="s">
</appwidget-provider>

Android12版本以上新增的2个属性,声明组件是4*2大小

  • targetCellWidth
  • targetCellHeight

4.清单文件声明

<receiverandroid:name=".view.CleaningWidget"android:enabled="true"android:exported="true"><intent-filter><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter><meta-dataandroid:name="android.appwidget.provider"android:resource="@xml/widget_info" />
</receiver>

5.代码添加小组件

官方说Android12不允许直接通过代码添加小组件,只能让用户手动去桌面拖动添加,但是我手头的三星系统却是支持的(也是Android12),具体还没有细究...

而官方文档上的写的例子如下:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {val context = this@DesktopWidgetActivityval appWidgetManager: AppWidgetManager =context.getSystemService(AppWidgetManager::class.java)val myProvider = ComponentName(context, CleaningWidget::class.java)//判断启动器是否支持小组件pinval successCallback = if (appWidgetManager.isRequestPinAppWidgetSupported) {// Create the PendingIntent object only if your app needs to be notified// that the user allowed the widget to be pinned. Note that, if the pinning// operation fails, your app isn't notified.Intent(context, CleaningWidget::class.java).let { intent ->// Configure the intent so that your app's broadcast receiver gets// the callback successfully. This callback receives the ID of the// newly-pinned widget (EXTRA_APPWIDGET_ID).//适配android12的val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {PendingIntent.FLAG_MUTABLE} else {PendingIntent.FLAG_UPDATE_CURRENT}PendingIntent.getBroadcast(context,0,intent,flags)}} else {null}appWidgetManager.requestPinAppWidget(myProvider, null, successCallback)
}

这里提下,上面的设置flags方法

val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {PendingIntent.FLAG_MUTABLE
} else {PendingIntent.FLAG_UPDATE_CURRENT
}

有个新项目的targetSdk为34(即Android14),如果使用上面的代码会出现下面崩溃错误提示

Targeting U+ (version 34 and above) disallows creating or retrieving a PendingIntent with FLAG_MUTABLE, an implicit Intent within and without FLAG_NO_CREATE and FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT for security reasons. To retrieve an already existing PendingIntent, use FLAG_NO_CREATE, however, to create a new PendingIntent with an implicit Intent use FLAG_IMMUTABLE.

实际上提示已经告诉我们怎么去改代码了,我这里把PendingIntent.FLAG_MUTABLE改为FLAG_IMMUTABLE就不会出现了上述的崩溃问题

应该是Android14添加的限制:

  • 如果Intent不传数据,必须使用PendingIntent.FLAG_IMMUTABLE
  • 如果是需要传递数据,则还是需要使用PendingIntent.FLAG_MUTABLE

定时刷新小组件UI

首先,我们得知道,如何主动去更新数据:

val context = it.context
val appWidgetManager: AppWidgetManager = context.getSystemService(AppWidgetManager::class.java)
val myProvider = ComponentName(context, CleaningWidget::class.java)
val remoview = CleaningWidget.getRemoteViewTest(context)//更新某类组件
appWidgetManager.updateAppWidget(myProvider,remoview)
//更新具体某个组件id
appWidgetManager.updateAppWidget(widgetId,remoview)

getRemoteViewTest方法就是创建一个remoteview,然后调用remoteview相关方法设置文本之类的进行数据填充,代码就略过不写了,详见上述基本步骤2

上面的方法我们注意到updateAppWidget可以传不同的参数,一般我们用的第二个方法,指定更新某个组件

但这里又是需要我们传一个组件id,所以就是在步骤2的时候,我们根据需要需要存储下widgetId比较好,一般存入数据库,或者使用SharePreference也可

然后,就是对于定时的情况和对应方案:

  1. 如果是间隔多长更新一次,可以使用开一个服务,在服务中开启协程进行
  2. 如果是单纯的时间文本更新,可以使用TextClock组件,比如说 12:21这种
  3. 小组件的xml中默认可以设置定时更新时长,不过最短只能需要15分钟
  4. 可以使用闹钟服务AlarmManager来实现定时,不过此用法需要结合pendingintent和广播接收器使用,最终要在广播接收器里调用更新数据方法
  5. JobScheduler来实现定时更新,似乎受系统省电策略影响,适用于不太精确的定时事件(官方文档上推荐这个)
  6. WorkManager来实现定时更新(实际上算是JobScheduler升级版),似乎受系统省电策略影响,适用于不太精确的定时事件

应该是除了第一种方法,其他都是可以在应用被杀死的情况进行更新小组件UI

小组件播放动画

progressbar实现

帧动画不手动调用anim.start()方法是不会播放的,然后在网上看到一篇文章,使用了progressbar来实现,步骤如下:

在drawable文件夹准备帧动画文件

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false" android:visible="true"><item android:drawable="@drawable/cat_1" android:duration="100" /><item android:drawable="@drawable/cat_2" android:duration="100" /><item android:drawable="@drawable/cat_3" android:duration="100" /><item android:drawable="@drawable/cat_4" android:duration="100" />
</animation-list>
<ProgressBarandroid:indeterminateDrawable="@drawable/cat_animdrawable"android:layout_width="wrap_content"android:layout_height="wrap_content"/>

indeterminateDrawable设置为上面的帧动画文件即可

layoutanim实现

主要是利用viewgroup的初次显示的时候,会展示当前view的添加动画效果,从而实现比较简单的动画效果,如平移,缩放等

可以看实现的敲木鱼一文Android-桌面小组件RemoteViews播放木鱼动画 - 掘金

使用ViewFlipper

ViewFlipper主要是轮播使用的

里面可放几个元素,之后通过设置autoStart为true,则保证自动轮播

flipInterval属性则是每个元素的间隔时间(帧动画的时间),单位为ms

不过在remoteview中使用的话,缺点就是里面的元素数目只能固定死

否则只能通过定义不同layout文件(如3个元素则是某个layout,4个元素则是某个layout,然后根据选择来创建remoteview)

<ViewFlipperandroid:id="@+id/viewFlipper"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_gravity="center"android:layout_margin="4dp"android:autoStart="true"android:flipInterval="800"><ImageViewandroid:id="@+id/vf_img_1"android:layout_width="match_parent"android:layout_height="match_parent"android:scaleType="fitXY"android:src="@drawable/peace_talisman_1" /><ImageViewandroid:id="@+id/vf_img_2"android:layout_width="match_parent"android:layout_height="match_parent"android:scaleType="fitXY"android:src="@drawable/peace_talisman_2" /></ViewFlipper>

补充

获取当前桌面的组件id列表

//获得当前桌面已添加的组件的id列表(可能用户添加了多个)
val context = it.context
val appWidgetManager: AppWidgetManager = context.getSystemService(AppWidgetManager::class.java)
val myProvider = ComponentName(context, CleaningWidget::class.java)val info =appWidgetManager.getAppWidgetIds(myProvider)
toast(info.size.toString())

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

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

相关文章

python数据可视化(7)——绘制箱形图

课程学习来源&#xff1a;b站up&#xff1a;【蚂蚁学python】 【课程链接&#xff1a;【【数据可视化】Python数据图表可视化入门到实战】】 【课程资料链接&#xff1a;【链接】】 Python绘制箱形图分析北京天气数据 箱形图 箱形图&#xff08;Box-plot&#xff09;又称为盒…

一站式短视频矩阵开发,高效托管!

短视频矩阵系统源码SaaS解决方案提供全面的开发服务&#xff0c;包括可视化视频编辑、矩阵式内容分发托管以及集成的多功能开发支持。 短视频矩阵&#xff1a;引爆您的数字营销革命 短视频矩阵系统是一套多功能集成解决方案&#xff0c;专为提升在短视频平台上的内容创作、管理…

【C++】多态-最全解析(多态是什么?如何使用多态?多态的底层原理是什么?)

目录 一、前言 二、多态是什么&#xff1f; 三、多态的定义及实现 &#x1f525; 多态的构成条件&#x1f525; &#x1f525; 虚函数的重写&#x1f525; &#x1f525;虚函数重写的两个例外 &#x1f525; &#x1f34d; 协变返回类型 &#x1f95d; 析构函数的重写…

使用APEXSQL LOG解析sql server事务日志,进行审计与数据恢复

一 下载 https://download.csdn.net/download/sunke861/11449739 二 使用 解压安装包后&#xff0c;点击&#xff1a;ApexSQLLog.exe 2.1 连接数据库 连接要审计的数据库&#xff1a; 假如报错&#xff1a; 则点击ok关闭该窗口&#xff0c;然后点击左上方的New按钮&#xf…

Git-Automatic merge failed; fix conflicts and then commit the result. 解决

Git-Automatic merge failed; fix conflicts and then commit the result. 解决 文章目录 1. 杂话2. 问题2.1 先搞定版本A2.2 再搞定版本AC2.3 搞定AB版本2.4 冲突 3. 解决3.1 分析3.2 解决 1. 杂话 大伙儿应该都用过Git吧&#xff0c;具体是个啥东西我就不说了哈。之前我在用g…

Codeforces Round 958 (Div. 2)(A~C)题

A. Split the Multiset 思路: 最优的策略是每次操作分出 k−1&#x1d458;−1 个 1&#xff0c;然后考虑最后是否会剩下一个单独的 1。 代码: #include<bits/stdc.h> using namespace std; #define N 1000005 typedef long long ll; typedef unsigned long long ull;…

【找不到视图问题解决】@RestController 与 @Controller注解的使用区别

一、问题描述 苍穹外卖在菜品分页查询功能实现的过程中&#xff0c;出现了找不到视图的情况 2024-07-12 21:54:20.860 ERROR 22488 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with p…

【Vim】为什么程序员喜欢用 Vim

1. Vim介绍 Vim是一款高度可配置的文本编辑器&#xff0c;它被设计成作为一个工具&#xff0c;可以非常高效地进行文本编辑工作。以下是关于Vim的一些基本介绍&#xff1a; 历史&#xff1a;Vim 是 Vi 文本编辑器的改进版&#xff0c;最初由布莱姆米勒&#xff08;Bram Moole…

Transformer注意力机制

Transformer注意力机制 &#x1f42c; 目录: 一、Transformer简介二、理解注意力机制自注意力机制多头注意力机制 一、Transformer简介 Transformer是一种用于自然语言处理(NLP)和其他序列到序列(Seq2Seq)任务的深度学习模型框架&#xff0c;它在2017年由Vaswani等人首次提出…

手机m4a怎么转换成mp3,手机端即可完成格式转换

M4A&#xff08;MPEG-4 Audio&#xff09;是一种无损压缩的音频格式&#xff0c;通常用于苹果设备和 iTunes 上&#xff0c;因为它能提供较高的音质同时占用较小的存储空间。 然而&#xff0c;MP3 作为最普及的音频格式之一&#xff0c;兼容性更强&#xff0c;几乎所有的播放设…

【单元测试】SpringBoot

【单元测试】SpringBoot 1. 为什么单元测试很重要&#xff1f;‼️ 从前&#xff0c;有一个名叫小明的程序员&#xff0c;他非常聪明&#xff0c;但有一个致命的缺点&#xff1a;懒惰。小明的代码写得又快又好&#xff0c;但他总觉得单元测试是一件麻烦事&#xff0c;觉得代码…

ENSP中NAT的相关实验(两个私网,一个公网)

题目 实验需求 1.按照图示配置IP地址&#xff0c;公网地址100.1.1.1/24 2.私网A通过NAPT&#xff0c;使R1接入到互联网&#xff0c;私网B通过EASY IP&#xff0c;使R3接入到互联网 3.私网A配置NAT SERVER把Telnet的Telnet服务发布到公网&#xff0c;使PC2可以访问 三、实验…

el-table和 el-image图片预览使用插槽后层叠样式错乱问题

问题&#xff1a; 解决办法&#xff1a;在el-image组件中添加preview-teleported 属性 最终效果

玩转鸿蒙NXET之组件导航与路由跳转二

页面路由&#xff08;ohos.router&#xff09; 页面路由指在应用程序中实现不同页面之间的跳转和数据传递。Router模块通过不同的url地址&#xff0c;可以方便地进行页面路由&#xff0c;轻松地访问不同的页面。本文将从页面跳转、页面返回、页面返回前增加一个询问框和命名路…

MongoDB自学笔记(一)

一、MongoDB简介 MongoDB是一款基于C开发的文档型数据库。与传统的关系型数据库有所不同&#xff0c;MongoDB面向的是文档&#xff0c;所谓的文档是一种名为BSON &#xff08;Binary JSON&#xff1a;二进制JSON格式&#xff09;是非关系数据库当中功能最丰富&#xff0c;最像…

AV1 编码标准帧间预测技术概述

AV1 编码标准帧间预测 AV1&#xff08;AOMedia Video1&#xff09;是一种开源的视频编码格式&#xff0c;它在帧间预测技术上做出了显著的改进和扩展&#xff0c;以提供比现有标准更高的压缩效率和更好的视频质量。以下是AV1帧间预测技术的几个关键点&#xff1a; 参考帧扩展&a…

You are running Vue in development mode.和undefined is not iterable白屏问题

遇到的报错信息如下&#xff0c; 你正在开发模式下运行 Vue。 确保在部署生产环境时打开生产模式 但是我是关闭了的Vue.config.productionTip false 最后发现是服务器问题

数据库作业6

视图作业 1. 创建视图v_emp_dept_id_1 CREATE VIEW v_emp_dept_id_1 AS SELECT emp_name, address FROM emp WHERE dept_id (SELECT dept_id FROM dept WHERE dept_name 销售部); 2. 创建视图v_emp_dept CREATE VIEW v_emp_dept AS SELECT e.emp_name, e.address, d.d…

AI艺术革命:使用神经网络生成创新艺术作品

如何使用神经网络生成艺术作品 1. 简介 神经网络&#xff0c;特别是卷积神经网络&#xff08;CNN&#xff09;和生成对抗网络&#xff08;GAN&#xff09;&#xff0c;在生成艺术作品方面表现出色。本教程将介绍如何使用这些神经网络生成艺术作品。 2. 基础概念 2.1 卷积神…

Ubuntu安装 Nginx

前置条件&#xff1a; 把apt包更新到最新&#xff08;如果更新过就跳过这步&#xff09; 先检查 sudo apt update 后更新 sudo apt upgrade &#xff08;期间要选择确认&#xff0c;输入 y 即可&#xff09; 如果不行可以&#xff1a;sudo apt upgrade --fix-missing 先卸…