介绍一下android桌面小组件完整的案例,包括:

  • 注册一个小组件(系统中能找到并添加小组件)
  • 更新小组件数据
  • 应用主动添加小组件
  • 小组件中的坑

AndroidManifest.xml:  (小组件注册, 其本质是一个BroadcastReceiver)

....
<receiver android:name=".appwidget.HanlonglinWidgetProvider"android:exported="false"><intent-filter><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter><meta-data android:name="android.appwidget.provider"android:resource="@xml/app_widget" />
</receiver>
....

xml/app_widget.xml: (小组件配置信息)

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"android:minWidth="90dp"android:minHeight="90dp"android:updatePeriodMillis="1800000"android:initialLayout="@layout/moment_widget_moment"android:widgetCategory="home_screen">
</appwidget-provider>
HanlonglinWidgetProvider.kt: (小组件绑定view的类)
package com.dragon.test.hanlonglindemo.appwidgetimport android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.RemoteViews
import com.dragon.test.hanlonglindemo.MainActivity
import com.dragon.test.hanlonglindemo.R/****  create by DragonForest on 2022/4/15*/
class HanlonglinWidgetProvider: AppWidgetProvider() {private val TAG = this.javaClass.simpleNameoverride fun onUpdate(context: Context?,appWidgetManager: AppWidgetManager?,appWidgetIds: IntArray?) {Log.i(TAG, "HanlonglinWidgetProvider.onUpdate")appWidgetIds?.forEach { appWidgetId ->val views: RemoteViews = RemoteViews(context?.packageName,R.layout.widget_layout)var intent = Intent(context, MainActivity::class.java)var pendingIntent = PendingIntent.getActivity(context,0,intent,PendingIntent.FLAG_UPDATE_CURRENT)views.setOnClickPendingIntent(R.id.iv_widget, pendingIntent)appWidgetManager?.updateAppWidget(appWidgetId, views)}}companion object{/*** 更新组件调用*/fun updateAppWidget(context: Context?,appWidgetManager: AppWidgetManager?,appWidgetId: Int,imgRes: Int){val views = RemoteViews(context!!.packageName, R.layout.widget_layout)views.setImageViewResource(R.id.iv_widget,imgRes)appWidgetManager?.updateAppWidget(appWidgetId,views)}}
}
WidgetController.kt: (小组件操作类)
package com.dragon.test.hanlonglindemo.appwidgetimport android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.annotation.RequiresApi/****  小组件操作类*  create by DragonForest on 2022/4/15*/
object WidgetController {private val TAG = this.javaClass.simpleName/*** 更新小组件,触发组件的onUpdate*/fun update(context: Context){var intent = Intent(context,HanlonglinWidgetProvider::class.java)intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATEvar bundle = Bundle()bundle.putIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS, getAppWidgetIds(context))intent.putExtras(bundle)context.sendBroadcast(intent)}/*** 添加到主屏幕*/@RequiresApi(Build.VERSION_CODES.O)fun addToMainScreen(context: Context){val appWidgetManager = AppWidgetManager.getInstance(context)val myProvider = ComponentName(context, HanlonglinWidgetProvider::class.java)if (getAppWidgetIds(context).isNotEmpty()) {Toast.makeText(context,"组件已经存在",Toast.LENGTH_SHORT).show()return}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. This callback receives the ID// of the newly-pinned widget (EXTRA_APPWIDGET_ID).
//            val successCallback = PendingIntent.getBroadcast(
//                /* context = */ context,
//                /* requestCode = */ 0,
//                /* intent = */ null,
//            /* flags = */ PendingIntent.FLAG_UPDATE_CURRENT)appWidgetManager.requestPinAppWidget(myProvider, null, null)}}private fun getAppWidgetIds(context: Context) :IntArray{var awm = AppWidgetManager.getInstance(context)val appWidgetIDs: IntArray = awm.getAppWidgetIds(ComponentName(context,HanlonglinWidgetProvider::class.java))return appWidgetIDs}
}
WidgetTestActivity.kt:  (测试页面,用来展示操作)
package com.dragon.test.hanlonglindemo.appwidgetimport android.app.Activity
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import com.dragon.test.hanlonglindemo.R
import kotlinx.android.synthetic.main.activity_widget_test.*/****  create by DragonForest on 2022/4/15*/
class WidgetTestActivity: Activity() {@RequiresApi(Build.VERSION_CODES.O)override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_widget_test)btn_add_to_screen.setOnClickListener {WidgetController.addToMainScreen(this)}}
}

注意的地方,

  • 小组件中只能使用指定的布局,不能使用类似ConstraintLayout等自定义布局详见:​​​​​​https://developer.android.com/guide/topics/appwidgets?hl=zh-cn#UpdatingFromTheConfiguration​​​​​​
  • 在应用中添加到桌面可能会失败,原因是小米等部分厂商禁用了桌面快捷方式权限,需要手动在应用信息中打开

更多信息:

Enable users to configure app widgets  |  Android Developers

Android 小组件完整案例相关推荐

  1. Android通用组件设计案例

    线程池设计 Glide:GlideExecutor

  2. 从 iOS 14 到 Android 12,桌面小组件是怎么「文艺复兴」的

    本文转载自 极客公园 时尚界一直以来有一个著名的理论:在某一时代流行的时尚元素,在经过一段时间的沉寂之后,会被人们再次拿出来利用. 这便是「弗莱定律」,它解释了为什么在长期的历史中,为什么很多曾经时尚 ...

  3. Android架构组件-App架构指南

    Android架构组件-App架构指南 Android架构组件-WorkManager Android架构组件- Room数据库的使用 Android架构组件-Lifecycle Android架构组 ...

  4. Android 12上焕然一新的小组件

    /   今日科技快讯   / 近日,电动汽车制造商特斯拉公布了2021年第三季度财报.财报显示,特斯拉第三季度营收137.6亿美元,同比增长57%:净利润16.2亿美元,同比增长389%:每股收益1. ...

  5. Android 12上焕然一新的小组件:美观、便捷和实用

    Google IO 2021上重磅介绍的Android 12,号称历代设计变化最大的版本.其全新的Material You设计语言.流畅的动画特效再到焕然一新的小组件,都令人印象深刻.本文将聚焦小组件 ...

  6. android桌面小组件开发_快使用Scriptable自己开发一个iPhone小组件吧

    最近苹果的 iOS 系统升级到了 iOS 14,这次的更新我比较关注的就是升级的小组件功能,这次更新我们可以将小组件放置在主屏幕中的任何位置,可以让我们更加便捷的查看一些信息,从而省去了还需要打开AP ...

  7. elementUI表格组件:自定义列模板(完整案例)

    elementUI表格组件:自定义列模板(含效果图) 所谓的自定义列模板,你也可以理解为自定义td的格式. 官方文档地址 :查看地址 页面· 效果图 · 对比 : 代码块1 · 对比:<temp ...

  8. android 组件消失了,Android 12 2.2 开发者预览版发布:修复桌面小组件消失等问题...

    IT 之家 4 月 8 日消息 据外媒 XDA 论坛消息,Android 12 2.2 开发者预览版今日发布,同时包含安卓 2021 年 4 月安全更新.本次预览版主要修复了一些错误,没有带来重要功能 ...

  9. 微信小程序云开发完整案例

    微信小程序云开发完整案例 本项目获高校微信小程序开发大赛华中赛区三等奖 [注]: 本人对该程序功能.UI等方面比较满意,分析总结了比赛成绩不算太好的原因,下一篇博客具体分享,给想参加该比赛的同学一些参 ...

  10. android 仿苹果 小组件,安卓玩烂的小组件 iOS怎么又给捡起来了?

    在所有用户的认知中,新系统区别于旧系统的第一印象永远是外观上的变化,例如iOS7的扁平化设计.iOS 10的控制中心.iOS 13的深色模式. 而在即将推出的iOS 14中,最直观的变化莫过于重新设计 ...

最新文章

  1. 小米Redmi Note 8 Pro!无套路包邮免费送!
  2. Matlab2018a求解一元二次方程
  3. phpstorm一个窗口打开多个项目
  4. scapy能干点啥?
  5. gridview中的图片错乱解决办法
  6. vue和aspx判断加页面传值.txt
  7. 计算机图形学实验报告百度云盘,计算机图形学实验报告(一).doc
  8. MAC编译lame ld: symbol(s) not found for architecture x86_64/_lame_init_old“, referenced from
  9. c语言题库-礼炮声响次数,c语言题库与答案精华版资料.doc
  10. 工程导论【职业能力与职业培养】
  11. 小米8 twrp recovery_小米max3一键刷入TWRP recovery 刷机教程
  12. Flink Web UI不能访问
  13. 区间调度问题(最大利润作业调度问题)
  14. Nessus之——Nessus的整理
  15. Java基础知识点总结(面试版)
  16. LinuxC——指针
  17. 值得 .NET 开发者了解的15个特性
  18. 关于接口自动化测试(2)
  19. 算法导论学习笔记1_循环不变式
  20. 「可口可乐 + Zion」7天上线小程序是如何做到的?

热门文章

  1. (1)Spring框架----通俗易懂的IoC原理
  2. ubuntu 18.04.1安装hadoop3.1.2
  3. Python运算符和表达式注意的地方
  4. P3200 [HNOI2009]有趣的数列
  5. liunx Swap 分区的作用
  6. RTX——第13章 事件标志组
  7. jquery ajax 方法及各参数详解
  8. C# abstract ,virtual ,override,new --比较好的文章
  9. [百万级]通用分页存储过程.[千万级]实现千万级数据的分页显示!
  10. 【C语言】19-static和extern关键字1-对函数的作用