2012-01-11 32 views
2

你好,我是新的widget編程,這讓我非常瘋狂! 我一直在試圖解決這個好幾天沒有希望,我發現的例子,其中很多,我測試,並從來沒有工作。我在模擬器和真實手機中都進行了測試。Android 2.2更新小部件從來不適合我

劇本很簡單,同樣的我已經隨處可見,甚至在這裏計算器,我在的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); 

所以代碼應該這樣工作:當我點擊小部件時,活動啓動,然後活動調用onUpdate函數來更新小部件,但小部件從不更新。

奇怪的是,log.v(「提供者」,「調用」顯示每次我點擊小部件,所以我非常確定onupdate被稱爲,但settextviewtext永遠不會工作,除了第一次時,小部件創建,任何想法?

回答