强制Android小部件更新

时间:2010-05-01 02:13:01

标签: android android-widget android-appwidget onupdate

我在onreceive方法中按下appwidget上的按钮。当我按下按钮时,我想强制小部件调用onupdate方法。我该如何做到这一点?

提前致谢!

2 个答案:

答案 0 :(得分:9)

Widget实际上无法响应点击,因为它不是一个单独的进程。但它可以启动服务来处理你的命令:

public class TestWidget extends AppWidgetProvider {
  public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int 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 UpdateService
            Intent intent = new Intent(context, UpdateService.class);
            PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

            // Get the layout for the App Widget and attach an on-click listener to the button
            RemoteViews views = new RemoteViews(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);
        }
    }

    public static class UpdateService extends Service {
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
          //process your click here
          return START_NOT_STICKY;
        }
    }
}

您还应该在清单文件中注册新服务:

<service android:name="com.xxx.yyy.TestWidget$UpdateService">

您可以在SDK

中的Wiktionary示例中找到另一个UpdateService实现示例

这是另一个好方法Clickable widgets in android

答案 1 :(得分:3)

这有点粗糙,但对我来说效果相当好,因为我没有找到直接实施的强制更新方式。

public class Foo extends AppWidgetManager {
   public static Foo Widget = null;
   public static Context context;
   public static AppWidgetManager AWM;
   public static int IDs[];

   public void onUpdate(Context context, AppWidgetManager AWM, int IDs[]) {
      if (null == context) context = Foo.context;
      if (null == AWM) AWM = Foo.AWM;
      if (null == IDs) IDs = Foo.IDs;

      Foo.Widget = this;
      Foo.context = context;
      Foo.AWM = AWM;
      Foo.IDs = IDs;
.......
   }
}

现在,在我想强制更新小部件的任何地方,它都很简单:

if (null != Foo.Widget) Foo.Widget.onUpdate(null, null, null);