android - 小部件 setOnClickPendingIntent 未启动服务

标签 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 服务的实现,但我看不到什么。还有人知道吗?

最佳答案

我已经设法解决了它

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 中这样做有什么问题。也许有人可以阐明原因。

关于android - 小部件 setOnClickPendingIntent 未启动服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13342158/

相关文章:

android - Square 的 Retrofit Android : Hash With Contents of Request

android - 如何在 Android 中全局锁定屏幕方向?

android - 连续线程监控硬件接近传感器

Java Gson 不兼容的类型

android - 在 ICS 中包含 fragment 的 native ActionBar 选项卡之间滑动

android - 如何强制重绘 ListView ?

android - 如何强制更新配置 Activity ?

android - 在后台估计信标检测器服务

android - 如何正确地将 ResultReceiver 子类发送到服务?

android - 我如何知道在通知中点击了哪个按钮?