2012-02-16 92 views
1

所以,我開發了一個應該作爲按鈕工作的android小部件。我使用這裏給出的基本代碼:http://developer.android.com/guide/topics/appwidgets/index.html 單擊按鈕時,將啓動一個活動。這每次都很好!但是,當我記錄點擊按鈕的時間時,我只能第一次得到它。爲什麼會發生?Android小部件onUpdate()

這裏是有人問我的代碼:

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

}

+0

沒有看到你的代碼,這不能回答。 – 2012-02-16 12:55:10

+0

我添加了一些代碼。正如我已經提到它只是Android教程 – JustCurious 2012-02-16 13:00:40

+0

Android文檔沒有功能來改變顏色或類似的東西。因此,您的代碼必須與文檔有所不同,並且必須以某種方式成爲潛在的原因*(並且我們需要查看該部分以幫助您)*。 – 2012-02-16 13:02:11

回答

0

該日誌語句是在widget的的onUpdate方法,並且在創建窗口小部件時纔會開始調用,在小部件的更新期間。要讓它登錄點擊,你可以做兩件事之一。

A.把日誌語句爲ExampleActivity

的onCreate方法

B.改變掛起意圖用標誌更新的AppWidgetProvider,然後覆蓋的onReceive方法做日誌statment,然後開始爲ExampleActivity,如果國旗是存在的。例如:

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

然後在的onReceive方法:

@Override 
public void onReceive(Context context, Intent intent) { 
    String action = intent.getAction(); 
    Bundle extras = intent.getExtras(); 

    if(AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action) && extras != null && extras.getBoolean(SOME_FINAL_STRING) == true){ 
     Log.d("myButton","Should no longer be called once!"); 
     Intent newIntent = new Intent(context, ExampleActivity.class); 
     newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     context.startActivity(newIntent); 
    } else { 
     super.onReceive(context, intent); 
    } 
}