Widget setOnClickPendingIntent not starting servic

2019-04-12 11:35发布

问题:

Following the example here i created my widget with ease.

I then added a button to my widget, this button should start a service so I added the following code to my 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);
}

The code certainly gets called, but service doesn't get started. I'm sure I have probably missed something with implementation of a service PendingIntent, but I can't see what. Anyone else know?

回答1:

Well I have managed to fix it

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

I am not entirely sure what was wrong with doing it in onEnable. Maybe someone can shed some light as to why.