美文网首页
Android- Widget (应用微件/小组件/插件) 使用

Android- Widget (应用微件/小组件/插件) 使用

作者: 行走中的3卡 | 来源:发表于2022-10-17 16:36 被阅读0次

    一、概念:

    App Widget 即叫 应用微件 或者 小组件/插件.
    是可以嵌入其他应用(如主屏幕)并 接收定期更新微型应用视图
    这些视图称为界面中的微件.
    例如,添加到桌面上的音乐Widget:

    app_widget_music_sample.PNG

    能够容纳其他应用微件的应用组件称为 AppWidgetHost (应用微件托管应用)
    App 通过传递要显示布局id 给RemoteViews, 即可以获取Widget的实例对象.

    官网介绍:
    指南:https://developer.android.com/guide/topics/appwidgets
    UI指南(更详细): https://developer.android.com/develop/ui/views/appwidgets/overview

    二、基础知识

    官网上的介绍顺序有点难懂,可以参考一下顺序,方便理解.

    要创建App Widget,大体需要以下三点:

    (1) 视图布局
    定义 Widget的布局 (xml)

    注意:
    这个布局需要添加到 RemoteViews, 而 RemoteViews 是不支持 ConstraintLayout的.
    支持:LinearLayout/FrameLayout/RelativeLayout/GridLayout, 以及TextView/Button等基础控件(不支持他们的子类)

    (2) AppWidgetProviderInfo 对象
    将数据封装在元素<appwidget-provider>里
    描述App Widget的元数据(meta-data),如布局、更新频率和 AppWidgetProvider 类。
    此对象应在 XML 中定义 并且 要在 AndroidManifest.xml中声明

    (3) AppWidgetProvider 类实现
    定义了 基于广播事件, 通知到 Widget 的方法。
    会在更新、启用、停用和删除 Widget 时收到广播。
    要在 AndroidManifest.xml中声明
    App可以通过它操作RemoteViews,例如更新等

    三、使用流程

    1. 创建Widget 内容的 布局

    /layout/widget_content.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <Button
            android:id="@+id/forward_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="这是一个测试的Widget内容 点击我快速使用 App 某个功能" />
    
    </RelativeLayout>
    

    2. 添加 AppWidgetProviderInfo 元数据

    数据封装在元素<appwidget-provider>里.
    /xml/example_appwidget_info.xml

    <?xml version="1.0" encoding="utf-8"?>
    <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
        android:initialKeyguardLayout="@layout/widget_content"
        android:initialLayout="@layout/widget_content"
        android:minHeight="110dp"
        android:minWidth="180dp"
        android:previewImage="@drawable/example_appwidget_preview"
        android:resizeMode="horizontal|vertical"
        android:updatePeriodMillis="0"
        android:widgetCategory="home_screen">
    
    </appwidget-provider>
    

    其中,
    (1) initialLayout 则表示 widget 显示的内容
    (2) minWidth / minHeight 表示Widget默认情况下,占用的最小空间. (最小大小不得超过 4 x 4 单元格)
    (3) previewImage 表示预览图片,即用户添加时展示的 (这里是example_appwidget_preview.png )
    (4) resizeMode 指定可以按什么规则来调整大小 (“horizontal”、“vertical”和“none”)
    (5) widgetCategory 是否可以显示在主屏幕(home_screen) 和/或锁定屏幕 (keyguard)
    注:这个XML 文件将会在AndroidManifest 声明 AppWidgetProvider组件时,由meta-data引用

    3. 使用 AppWidgetProvider 类

    AppWidgetProvider 类扩展了 BroadcastReceiver, 作为一个辅助类来处理应用微件广播。
    仅接收与Widget有关的事件广播,例如当更新、删除、启用和停用Widget时发出的广播.

    当发生这些广播事件时,AppWidgetProvider 会接收以下方法调用:
    onUpdate()
    onAppWidgetOptionsChanged()
    onDeleted(Context, int[])
    onEnabled(Context)
    onDisabled(Context)
    onReceive(Context, Intent)

    最重要的是 onUpdate, 如果要处理任何用户交互事件,都需要在此回调处理.
    这里我们设置,点击了Widget 后,跳转到 ExampleActivity 里.

    class ExampleAppWidgetProvider : AppWidgetProvider() {
    
        override fun onUpdate(
            context: Context,
            appWidgetManager: AppWidgetManager,
            appWidgetIds: IntArray
        ) {
            // Perform this loop procedure for each App Widget that belongs to this provider
            appWidgetIds.forEach { appWidgetId ->
                // Create an Intent to launch ExampleActivity
                val pendingIntent: PendingIntent = Intent(context, ExampleActivity::class.java)
                    .let { intent ->
                        PendingIntent.getActivity(context, 0, intent,
                            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) // set flags to fix fatal when sdk >=31
                    }
    
                // Get the layout for the App Widget and attach an on-click listener
                // to the button
                val views: RemoteViews = RemoteViews(
                    context.packageName,
                    R.layout.widget_content
                ).apply {
                    setOnClickPendingIntent(R.id.forward_button, pendingIntent)
                }
    
                // Tell the AppWidgetManager to perform an update on the current app widget
                appWidgetManager.updateAppWidget(appWidgetId, views)
            }
        }
    }
        
    

    其中,
    (1) appWidgetIds 是一个ID 数组,对应每一添加到主屏幕的Widget实例.
    (即:可以在主屏幕添加 多个Widget)
    (2) 不同的Widget 实例,updatePeriodMillis 更新周期表依照第一个Widget实例.
    (3) pendingIntent 用于点击Widget上的Button时,跳转到ExampleActivity
    注意:在SDK>=31 上,需要设置 FLAG_IMMUTABLE. 否则会出现fatal error:Strongly consider using FLAG_IMMUTABLE...
    (4) ExampleActivity 是一个简单的Activity,
    代码:

    class ExampleActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_example)
        }
    }
    

    activity_example 为布局资源,仅显示一个TextView

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ExampleActivity">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Show this From Widget!!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    4. 在AndroidManifest中声明 AppWidgetProvider 并声明 AppWidgetProviderInfo

            <receiver android:name="ExampleAppWidgetProvider"
                android:exported="true">
                <intent-filter>
                    <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                </intent-filter>
                <meta-data android:name="android.appwidget.provider"
                    android:resource="@xml/example_appwidget_info" />
            </receiver>
    

    需要在清单中声明后,才能在小组件设置里添加.

    此处的声明可以反推出来:
    (1) App Widget的入口,其实依赖 <intent-filter>里声明的action:android.appwidget.action.APPWIDGET_UPDATE
    (2)猜测系统(Launcher) 将会遍历所有的AndroidManifest, 然后找到有这个action所在的组件.
    在用户长按应用图标时,可显示应用 自定义的组件。
    (3)而这个自定义组件的内容是 从 meta-data里的 "android.appwidget.provider" 读取出来。
    (4)后续,有小组件的事件,则是通知到它所声明的receiver (这里是ExampleAppWidgetProvider)

    至此,已经完成所有,
    运行app即可体验.

    5. 效果图如下:

    (1)添加Widget


    demo_add widget.PNG

    (2) 添加Widget时的 预览图


    add widget preview.PNG

    (3) Widget 显示图


    widget_in home screen.PNG

    (4) 点击Widget的button 后则会跳转的对应的Activity

    相关文章

      网友评论

          本文标题:Android- Widget (应用微件/小组件/插件) 使用

          本文链接:https://www.haomeiwen.com/subject/ztddzrtx.html