AppWidget入门

Appwidget本质上还是一个广播:

定义一个appwidget的方式如下:

1,首先创建一个类,继承AppWidgetProvider,在其中重写需要重写的方法

2,res下建立xml文件夹,建立元数据。包括指定高度,初始布局等等。

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minHeight="80px"
android:minWidth="300px"
android:updatePeriodMillis="6000"
android:initialLayout="@layout/mywidget">
</appwidget-provider>

3,其中的初始布局需要在layout文件夹下建立

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="click" />

</LinearLayout>

这里补充,appwidget的生命周期

如果是第一次向桌面添加一个widget:将依次调用onreceive,oncreate,onreceive,onupdate方法

如果向桌面添加一个相同的widget,将依次调用onreceive,onupdate方法

如果删除一个widget,将依次调用onreceive,ondeleted方法

如果将桌面上同样的widget都删除干净的时候,将会调用onreceive,ondisabled方法

由此可见,每次添加组件都会调用onupdate方法,因此一般需要将该方法进行重写。

4,在配置文件中配置receiver节点。

     <receiver android:name=".MyAppWidget" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_manage" />
        </receiver>
原文地址:https://www.cnblogs.com/bobodeboke/p/3005963.html