窗口小部件setOnClickPendingIntent无法启动服务

时间:2012-11-12 10:35:18

标签: android android-widget android-service android-pendingintent

按照示例here,我轻松创建了我的小部件。

然后我在我的小部件中添加了一个按钮,这个按钮应该启动一个服务,所以我将以下代码添加到我的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服务的实现,但是我看不清楚。其他人都知道吗?

1 个答案:

答案 0 :(得分: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中执行此操作有什么问题。也许有人可以解释为什么。