Android 2.2更新小部件永远不适合我

时间:2012-01-11 18:04:22

标签: android android-widget

您好我是小部件编程的新手,这让我真的很疯狂! 我一直试图在没有希望的情况下解决这个问题,我找到了一些例子 - 很多例子 - 我测试过,而且从不工作。我在模拟器和真实手机中进行了测试。

脚本很简单,就像我到处找到的一样,即使在stackoverflow中,我在onUpdate中有一个小脚本

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 some random data
            int number = (new Random().nextInt(100));

     Log.v("Provider", "called");

     // Get the layout for the App Widget and attach an on-click listener
    // to the button
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widgetlayout);

    views.setTextViewText(R.id.textViewwid, String.valueOf(number));

        // Create an Intent to launch ExampleActivity
    Intent intent = new Intent(context, HelloAndroidActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.textViewwid, pendingIntent);



    // Tell the AppWidgetManager to perform an update on the current app widget
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

然后在我的活动的某个地方,我想更新小部件

    Log.v("Response", "my activity lunched");
   // Find widget id from launching intent
    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if (extras != null) {
        mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
    }

    // If they gave us an intent without the widget id, just bail.
    if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
        Log.v("Response", "no appwidget id provided");
        finish();
    }

    //configureWidget(getApplicationContext());
    Log.v("Response", "appwidget id is provided!!");

    // Make sure we pass back the original appWidgetId before closing the activity
    Intent resultValue = new Intent(this, WidgetProvider.class);
    //resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);


    resultValue.setAction("android.appwidget.action.APPWIDGET_UPDATE");
 int[] ids = {mAppWidgetId};
 resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids);
 sendBroadcast(resultValue);

因此代码应该以这种方式工作:当我单击小部件时,Activity启动,然后活动调用onUpdate函数来更新小部件,但小部件永远不会更新。

奇怪的是log.v(每次点击窗口小部件时都显示“提供者”,“被叫”,所以我非常肯定会调用onupdate,但是settextviewtext永远不会工作,除了第一次小部件是创建的,任何想法??

1 个答案:

答案 0 :(得分:2)

我在更新活动中的小部件时遇到了同样的问题。在下面的主题中查看dave.c的答案。他的updateAllWidgets函数在这个问题上是一个救命的答案。

android appwidget won't update from activity