android - 强制 Android 小部件更新

标签 android android-widget android-appwidget onupdate

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

提前致谢!

最佳答案

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;
        }
    }
}

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

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

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

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

关于android - 强制 Android 小部件更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2748613/

相关文章:

android - 为什么我的动画不会在给定的 to-x 值处停止?

android - 仅允许在批准的设备上登录 Android 应用程序

android - android中的富文本框

android - 应用程序小部件中的 ViewFlipper

Android - 在图像/缩略图上覆盖播放按钮的最佳方式

android - 需要创建类似控件的电子表格,我应该扩展 ListView 或 GridView 什么?

android.database.sqlite.SQLiteCursor@435b9ba0

android - setCompoundDrawables 与 RemoteViews

android - 如何像 Activity 一样在主屏幕小部件中使用按钮

java - onNotificationPosted 一段时间后没有被调用