?1、AppWidgetProvider :继承自 BroadcastRecevier ,
在AppWidget 应用 update、enable、disable 和 delete 时接收通知。
其中,onUpdate、onReceive 是最常用到的方法,它们接收更新通知。
//点击桌面组件时进入主程序入口:
onUpdate
当App Widget从宿主中删除时被调用。
onDeleted
当一个App Widget实例第一次创建时被调用。
比如,如果用户添加两个App Widget实例,只在第一次被调用。
如果你需要打开一个新的数据库或者执行其他对于所有的App Widget实例只需要发生一次的设置,
那么这里是完成这个工作的好地方。
onEnabled
这里可以start一个service。
当你的App Widget的最后一个实例被从宿主中删除时被调用。你应该在onEnabled(Context)中做一些
清理工作,比如删除一个临时的数据库。
onDisabled
这里可以stop掉已启动的service。
接收到每个广播时都会被调用,而且在上面的回调函数之前。
你通常不需要实现这个方法,因为缺省的AppWidgetProvider实现过滤所有App Widget广播并恰当的调用上述方法。
onReceive
AppWidgetManger :负责管理 AppWidget ,向 AppwidgetProvider 发送通知。
?updateAppWidget(ComponentName provider, RemoteViews views)
通过 ComponentName 对传进来的 RemoeteView 进行修改,并重新刷新AppWidget 组件
//RemoteViews类描述了一个View对象能够显示在其他进程中,可以融合layout资源文件实现布局。
//虽然该类在android.widget.RemoteViews而不是appWidget下面,但在Android Widgets开发中会经常用到它,
//主要是可以跨进程调用(appWidget由一个服务宿主来统一运行的)。
RemoteViews myRemoteViews = new RemoteViews(context.getPackageName(), R.layout.my_layout);
在xml声明类似如下:
<receiver
android:name=".WeatherWidget"
android:label="Weather">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/appwidget_provider"/>
home是按home键响应,LAUNCHER是开机自动启动
<categoryandroid:name="android.intent.category.HOME" />
<categoryandroid:name="android.intent.category.LAUNCHER" />
//点击桌面组件时进入主程序入口
Intent intent=new Intent(context, MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(context, 0, intent, 0);
//RemoteViews类描述了一个View对象能够显示在其他进程中,可以融合layout资源文件实现布局。
//虽然该类在android.widget.RemoteViews而不是appWidget下面,但在Android Widgets开发中会经常用到它,
//主要是可以跨进程调用(appWidget由一个服务宿主来统一运行的)。
RemoteViews myRemoteViews = new RemoteViews(context.getPackageName(), R.layout.my_layout);
//myRemoteViews.setImageViewResource(R.id.imageView, R.drawable.png1);//设置布局控件的属性(要特别注意)
myRemoteViews.setOnClickPendingIntent(R.id.btn, pendingIntent);
ComponentName myComponentName = new ComponentName(context, TestActivity.class);
//负责管理AppWidget,向AppwidgetProvider发送通知。提供了更新AppWidget状态,获取已经安装的Appwidget提供信息和其他的相关状态
AppWidgetManager myAppWidgetManager = AppWidgetManager.getInstance(context);
myAppWidgetManager.updateAppWidget(myComponentName, myRemoteViews);