10

onreceive メソッドで appwidget のボタンを押すと応答します。ボタンを押したときに、ウィジェットに強制的に onupdate メソッドを呼び出してもらいたいです。どうすればこれを達成できますか?

前もって感謝します!

4

2 に答える 2

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

また、新しいサービスをマニフェスト ファイルに登録する必要があります。

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

SDK のウィクショナリー サンプルで UpdateService 実装の別の例を見つけることができます。

そして、ここに別の良いアプローチがあります Androidのクリック可能なウィジェット

于 2010-05-01T03:13:40.267 に答える
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);
于 2010-11-11T23:31:14.070 に答える