3

繼示例here我輕鬆創建了我的小部件。小部件setOnClickPendingIntent未啓動服務

我加入一個按鈕控件我,這個按鈕應該啓動一個服務,所以我下面的代碼添加到我的WidgetProvider

@Override 
public void onEnabled(Context context) { 
    Log.e("ERROR", "REMOVE ME"); // TODO remove. This is for eclipse logcat recognition 
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); 

    Intent intent = new Intent(context, RepairService.class); 
    PendingIntent pi = PendingIntent.getService(context, 0, intent, 0); 
    views.setOnClickPendingIntent(R.id.widget_boost, pi); 
} 

的代碼肯定會被調用,但服務不上手。我確定我可能錯過了一個服務PendingIntent的實現,但我看不到。其他人知道嗎?

回答

4

嗯,我設法解決它

public class WidgetProvider extends AppWidgetProvider { 

@Override 
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, 
     int[] appWidgetIds) { 

    Log.e("ERROR", "onUpdate method called"); 

    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 ExampleActivity 
     Intent intent = new Intent(context, UpdateService.class); 
     PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0); 
     Log("Pending Intent = " + pendingIntent.toString()); 

     // Get the layout for the App Widget and attach an on-click listener to the button 
     RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); 
     views.setOnClickPendingIntent(R.id.widge, 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 void onCreate() { 
       ......... 
       ......... 
      } 

      // Service stuff here 
    } 
} 

我不完全知道什麼是錯在onEnable這樣做。也許有人可以闡明爲什麼。