力的Andr​​oid窗口小部件更新部件、窗口、Andr、oid

2023-09-06 00:29:05 作者:半夜走在路上誰都像Sé狼

我到一个按钮preSS回应我在的onReceive方法appwidget。当按钮I pressed,我想迫使小部件调用的OnUpdate方法。我如何做到这一点?

I respond to a button press on my appwidget in the onreceive method. When the button I pressed, I want to force the widget to call the onupdate method. How do I accomplish this?

在此先感谢!

推荐答案

小工具无法真正的点击响应,因为它不是一个单独的进程运行。但它可以启动服务来处理您的命令:

Widget can't actually respond to clicks because it's not a separate process running. But it can start service to process your command:

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

您也应该在清单文件注册新的服务:

You should also register the new service in your manifest file:

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

您可以找到UpdateService实施维基样品中SDK

You can find another example of UpdateService implementation in Wiktionary sample in SDK

和这里的另一个好办法Clickable在Android的部件

And here's another good approach Clickable widgets in android