紧接上集,appwidget的周期函数对应的事件:
onUpdate:到达指定时间以后或者用户向桌面添加appwidget时候会调用这个方法。
onDelete:当appwidget被删除时,会调用这个方法。
onEnable:当一个appwidget第一次被建立,会调用这个方法。
onDisable:当最后一个appwidget实例被删除后,会调用这个方法。
onReveice:接受广播事件。
调试出来了么?
这集内容是如何与appwidget交互:
咱们实现的功能是建立一个appwidget(为一个button),点击后,启动一个activity。
一样是新知识介绍:
一、咱们的appwidget与咱们对应的activity不是同一个进程,appwidget是homescreen中的一个进程。因此,咱们不能直接对某一个控件进行事件监听,而是经过RemoteViews进行处理,并且咱们也不能直接用intent进行启动activity,用pendingintent。
二、pendingintent:顾名思义,是还未肯定的Intent。能够看作是对intent的一个包装,目的是对RemoteViews进行设置。形象点讲就是咱们进程A中的intent想要在进程B中执行,须要pendingintent进行包装,而后添加到进程B中,进程B中遇到某个事件,而后执行intent。
建立pendingintent有三个方法:getActivity(context,requestCode,intent,flags)。getService()。getBroadcast()。
三、RemoteViews:即远程的views。他的做用是他所表示的对象运行在另外的进程中。
如今话很少说,果断代码:
一、咱们在上集的appwidget.xml中(即桌面控件上加上一个Button)代码:
- <span style="font-size: x-small;"> <Button
- android:id="@+id/button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="测试按钮"
- /></span>
<Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试按钮" />
二、咱们在provider中的onUpdate方法中进行处理:java
- <span style="font-size: x-small;">for(int i= 0;i<appWidgetIds.length;i++){
- System.out.println(appWidgetIds[i]);
- //新intent
- Intent intent = new Intent(context,Appwidget2Activity.class);
- //建立一个pendingIntent。另外两个参数之后再讲。
- PendingIntent pendingIntent = PendingIntent.getActivity(
- context, 0, intent, 0);
- //建立一个remoteViews。
- RemoteViews remoteViews = new RemoteViews(
- context.getPackageName(), R.layout.appwidget);
- //绑定处理器,表示控件单击后,会启动pendingIntent。
- remoteViews.setOnClickPendingIntent(R.id.button, pendingIntent);
- appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
- }</span>
for(int i= 0;i<appWidgetIds.length;i++){ System.out.println(appWidgetIds[i]); //新intent Intent intent = new Intent(context,Appwidget2Activity.class); //建立一个pendingIntent。另外两个参数之后再讲。 PendingIntent pendingIntent = PendingIntent.getActivity( context, 0, intent, 0); //建立一个remoteViews。 RemoteViews remoteViews = new RemoteViews( context.getPackageName(), R.layout.appwidget); //绑定处理器,表示控件单击后,会启动pendingIntent。 remoteViews.setOnClickPendingIntent(R.id.button, pendingIntent); appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews); }
由于咱们可能有多个appwidget,因此要遍历。建立一个intent,与要启动的activity关联起来,而后根据该intent建立一个pendingintent。而后根据appwidget.xml建立一个remoteViews,而后对该views中的一个控件进行pendingintent绑定。android