Android小部件onUpdate()

时间:2012-02-16 12:53:24

标签: android android-widget onupdate

所以,我开发了一个应该用作按钮的android小部件。我使用了这里给出的基本代码:http://developer.android.com/guide/topics/appwidgets/index.html 单击该按钮时,将启动一个活动。这次每次都很好!但是,当我记录单击按钮的时间时,我只是第一次获得。为什么会这样?

以下是我被要求的代码:

public class ExampleAppWidgetProvider 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];
        Log.d("myButton","This is only called once.Why????????")
        // Create an Intent to launch ExampleActivity
        Intent intent = new Intent(context, ExampleActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(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);
    }
}

}

1 个答案:

答案 0 :(得分:0)

该日志语句位于窗口小部件的onUpdate方法中,并且仅在创建窗口小部件时以及窗口小部件的更新周期中最初调用。要让它登录,请点击,您可以执行以下两项操作之一。

一个。将日志语句放在ExampleActivity的onCreate方法

B中。更改挂起的意图以使用标志更新AppWidgetProvider,然后覆盖onReceive方法以执行日志声明,然后启动ExampleActivity(如果标志存在)。例如:

continue

然后在onReceive方法中:

Intent intent = new Intent(context, ExampleAppWidgetProvider.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(SOME_FINAL_STRING, true);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);