android学习之widget3

来源:互联网 发布:linux安装eclipse 编辑:程序博客网 时间:2024/06/05 07:55

Adding margins to App Widgets

这里既可以使用android:padding属性也可以在background中指定一个NinePatch图片

Using the AppWidgetProvider Class

AppWidgetProvider类继承自BroadcastReceiver:

onUpdate():更新和用户初始添加的时候调用,如果有configure activity,则用户添加时不会被调用。在这个方法里可以定义事件处理器,启动临时service。

onDeleted(Context, int[])

onEnabled(Context):只在第一次初始化App Widget的时候调用,如果添加两次也只会调用一次

onDisabled(Context):最后一个App Widget被删除的时候调用

onReceive(Context, Intent):在前面所有回调方法之前执行,不需要实现

public classExampleAppWidgetProvider extends AppWidgetProvider{   

                 publicvoid onUpdate(Context context,AppWidgetManager appWidgetManager,int[] appWidgetIds){       

                           finalint N = appWidgetIds.length;       

                           // Perform this loop procedure for each App Widget that belongs to this provider       

                           for(int i=0; i<N; i++) {           

                                 int appWidgetId= appWidgetIds[i];           

                                 // Create an Intent to launch ExampleActivity           

                                 Intent intent= newIntent(context,ExampleActivity.class);           

                                 PendingIntent pendingIntent= PendingIntent.getActivity(context,0, intent,0);           

                                 // Get the layout for the App Widget and attach an on-click listener           

                                 // to the button           

                                 RemoteViews views= newRemoteViews(context.getPackageName(), R.layout.appwidget_provider_layout);           

                                 views.setOnClickPendingIntent(R.id.button, pendingIntent);           

                                 // Tell the AppWidgetManager to perform an update on the current app widget           

                                appWidgetManager.updateAppWidget(appWidgetId, views);       

                             }   

                 }

}

for循环保证每个appWidgetIds中的实例都能同步更新,但是更新时间会按照第一个实例算

启动service的例子去访问Wiktionary sample's AppWidgetProvider

Receiving App Widget broadcast Intents

AppWidgetProvider只是一个方便的类而已。如果你想直接接收App Widget的广播,你可以实现自己的BroadcastReceiver或者重写onReceive(Context, Intent)方法

需要考虑四个Intents:

  • ACTION_APPWIDGET_UPDATE
  • ACTION_APPWIDGET_DELETED
  • ACTION_APPWIDGET_ENABLED
  • ACTION_APPWIDGET_DISABLED

     

     

  • 原创粉丝点击