Widget就是可以放在桌面上的组件,包括像天气、便签、日历、垃圾清理、快速搜索等等,都是Widget。
Github Demo地址
AppWidgetProvider
定义允许您基于广播事件以编程方式与应用微件连接的基本方法。
在Android studio中创建Widget组件
创建Widget的主要3个文件:
1.得到生成的AppWidgetProvider类:
class GoogleSearchWidget : AppWidgetProvider() {
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
//此方法可以按 AppWidgetProviderInfo 中的 updatePeriodMillis 属性定义的时间间隔来更新应用微件
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
override fun onReceive(context: Context?, intent: Intent?) {
super.onReceive(context, intent)
//接收广播
}
override fun onEnabled(context: Context) {
// 首次创建应用微件的实例时,会调用此方法。
}
override fun onDisabled(context: Context) {
// 从应用微件托管应用中删除了应用微件的最后一个实例时,会调用此方法。
}
/*
* 每删除一次窗口小部件就调用一次
*/
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
}
/*
* 当小部件大小改变时
*/
@Override
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
}
}
internal fun updateAppWidget(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int
) {
val views = RemoteViews(context.packageName, R.layout.google_search_widget)
appWidgetManager.updateAppWidget(appWidgetId, views)
}
Widget继承于BroadcastReceiver,需要在manifest中注册:
android:name指定元数据名称。使用 android.appwidget.provider将数据标识为 AppWidgetProviderInfo描述符。
android:resource`指定 AppWidgetProviderInfo资源位置。
android:name=".GoogleSearchWidget" android:exported="false"> android:name="android.appwidget.provider" android:resource="@xml/google_search_widget_info" />
创建Widget同时会创建AppWidgetProviderInfo文件,描述应用微件的元数据,如应用微件的布局、更新频率和 AppWidgetProvider 类。
android:description="@string/app_widget_description" android:initialKeyguardLayout="@layout/google_search_widget" android:initialLayout="@layout/google_search_widget" android:minWidth="250dp" android:minHeight="40dp" android:previewImage="@drawable/example_appwidget_preview" android:previewLayout="@layout/google_search_widget" android:resizeMode="horizontal|vertical" android:targetCellWidth="4" android:targetCellHeight="1" android:updatePeriodMillis="86400000" android:widgetCategory="home_screen" /> 属性解释 minWidth 和 minHeight 属性的值指定应用微件默认情况下占用的最小空间 minResizeWidth 和 minResizeHeight 属性指定应用微件的绝对最小大小。 updatePeriodMillis 属性定义应用微件框架通过调用 onUpdate()回调方法来从 AppWidgetProvider请求更新的频率应该是多大。不能保证实际更新按此值正好准时发生,我们建议尽可能降低更新频率 - 或许不超过每小时一次,以节省电池电量。 initialLayout 属性指向用于定义应用微件布局的布局资源。 previewImage 属性指定预览来描绘应用微件经过配置后是什么样子的,用户在选择应用微件时会看到该预览。 创建Widget布局 Widget基于RemoteViews类,并不支持所有的控件跟布局,而仅仅只是支持Android布局和控件的一个子集。 1、支持布局:FrameLayout,LinearLayout,RelativeLayout,GridLayout 2、支持控件:AnalogClock,Button,Chronometer,ImageButton,ImageView,ProgressBar,TextView,ViewFlipper,ListView,GridView,StackView,AdapterViewFlipper 布局控件使用超出限制,或者使用了自定义View, 添加控件时会报"找不到布局"的错误: 简单示例布局文件: xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="55dp" android:id="@android:id/background" android:background="@drawable/shape_corner_30_solid_white" android:orientation="horizontal" android:padding="10dp" android:gravity="center_vertical"> android:id="@+id/iv_google_search" android:layout_width="30dp" android:layout_height="30dp" android:src="@mipmap/google" android:layout_marginStart="5dp"/> android:layout_width="0dp" android:layout_weight="1" android:layout_height="1dp"/> android:layout_width="30dp" android:layout_height="30dp" android:src="@mipmap/voice"/> android:layout_width="30dp" android:layout_height="30dp" android:src="@mipmap/camera" android:layout_marginStart="10dp" android:layout_marginEnd="5dp"/> 从小部件库中添加到桌面效果: 在代码中动态添加到桌面: /** * 动态向桌面添加widget */ @JvmStatic fun createDeskTopWidget() { appContext?.let { val serviceComponent = ComponentName(it, GoogleSearchWidget::class.java) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { AppWidgetManager.getInstance(appContext).requestPinAppWidget(serviceComponent, null, null) } } } requestPinAppWidget: Request to pin an app widget on the current launcher. It's up to the launcher to accept this request (optionally showing a user confirmation) 点击事件跳转 点击iv_google_search为id的控件,这里通过action匹配目标activity,创建PendingIntent进行跳转,可通过给intent携带extra进行传参。 internal fun updateDeskTopWidget( context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int ) { val views = RemoteViews(context.packageName, R.layout.browser_desktop_widget) views.setOnClickPendingIntent(R.id.iv_google_search, getPendingIntentByAction(context, R.id.iv_google_search, ACTION_SEARCH, MODE_BROWSER_SEARCH)) appWidgetManager.updateAppWidget(appWidgetId, views) } fun getPendingIntentByAction(context: Context, appWidgetId: Int, action: String, extra: String): PendingIntent { val intent = Intent() intent.action = action intent.putExtra("extra", extra) //使用FLAG_ACTIVITY_CLEAR_TOP会将该启动的activity上层activity弹出栈,确保该activity能显示在顶层 intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP var flag = PendingIntent.FLAG_UPDATE_CURRENT if (android.os.Build.VERSION.SDK_INT >= 31) { flag = flag or PendingIntent.FLAG_MUTABLE } return PendingIntent.getActivity( context, appWidgetId, intent, flag ) } 进程初始化处理 由于Widget在子进程中创建,所以在创建widget进程的时候,会重复走application的oncreate方法,初始化也会走多次,所以导致widget进程会初始化很多不必要的内容,占用过多内存。所以需要在application的onCreate方法中判断当前进程是否是widget进程,如果是widget进程,直接return。 Widget进行周期性更新内容 在App中发送广播,在widget中的onReceive() 用来接收广播。 Intent updateIntent = new Intent(ACTION_UPDATE); sendBroadcast(updateIntent); AppWidgetProvider中代码: class GoogleSearchWidget : AppWidgetProvider() { // 保存 widget 的id的HashSet,每新建一个 widget 都会为该 widget 分配一个 id。 private val idsSet = HashSet companion object { const val ACTION_UPDATE = "action_update" } override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { //此方法可以按 AppWidgetProviderInfo 中的 updatePeriodMillis 属性定义的时间间隔来更新应用微件 for (appWidgetId in appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId) idsSet.add(appWidgetId) //更新控件存储 appWidgetId } } override fun onEnabled(context: Context) { // 首次创建应用微件的实例时,会调用此方法。 } override fun onDisabled(context: Context) { // 从应用微件托管应用中删除了应用微件的最后一个实例时,会调用此方法。 } override fun onReceive(context: Context, intent: Intent?) { super.onReceive(context, intent) if (intent?.action.equals(ACTION_UPDATE)) { updateAllAppWidgets(context, AppWidgetManager.getInstance(context)) } } /** * 更新所有widget */ private fun updateAllAppWidgets(context: Context, appWidgetManager: AppWidgetManager) { idsSet.forEach { val views = RemoteViews(context.packageName, R.layout.google_search_widget) appWidgetManager.updateAppWidget(it, views) // 更新 widget } } } 最后,需要启动周期性任务来更新widget广播触发,可以选择启动service,在service启动timer周期性发送,可以利用Alarm来周期性发送,还可以使用Workmanager做周期性任务发送广播。