Android widget开发指南

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资源位置。
        <receiver
            android:name=".GoogleSearchWidget"
            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/google_search_widget_info" />
        </receiver>

创建Widget同时会创建AppWidgetProviderInfo文件,描述应用微件的元数据,如应用微件的布局、更新频率和 AppWidgetProvider 类。

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    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, 添加控件时会报"找不到布局"的错误:
简单示例布局文件:
<LinearLayout
    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">

    <ImageView
        android:id="@+id/iv_google_search"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:src="@mipmap/google"
        android:layout_marginStart="5dp"/>

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="1dp"/>

    <ImageView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:src="@mipmap/voice"/>

    <ImageView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:src="@mipmap/camera"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="5dp"/>
</LinearLayout>
从小部件库中添加到桌面效果:
在代码中动态添加到桌面:
        /**
         * 动态向桌面添加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<Int>()
    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做周期性任务发送广播。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容