强制Android小部件更新

str*_*ark 10 android onupdate android-widget android-appwidget

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

提前致谢!

Fed*_*dor 9

小部件实际上无法响应点击,因为它不是一个单独的进程运行.但它可以启动服务来处理您的命令:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<service android:name="com.xxx.yyy.TestWidget$UpdateService">
Run Code Online (Sandbox Code Playgroud)

您可以在SDK中的Wiktionary示例中找到另一个UpdateService实现示例

是Android中另一个很好的方法Clickable小部件