3

当我在调试模式下运行时,我似乎无法到达服务内部的任何断点,这是为什么呢?

    @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    context.startService(new Intent(context, UpdateService.class));
}

public static class UpdateService extends Service {

    @Override
    public void onStart(Intent intent, int startId) {
        // Build the widget update for today
        RemoteViews updateViews = buildUpdate(this);

        // Push update for this widget to the home screen
        ComponentName thisWidget = new ComponentName(this, WidgetProvider.class);
        AppWidgetManager manager = AppWidgetManager.getInstance(this);
        manager.updateAppWidget(thisWidget, updateViews);
    }

    public RemoteViews buildUpdate(Context context) {
        return new RemoteViews(context.getPackageName(), R.id.widget_main_layout);
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
4

3 回答 3

2

Service可能未在清单中注册。或者您AppWidgetProvider可能没有在清单中注册。

于 2011-02-24T15:12:59.340 回答
2

“onUpdate”方法仅在小部件被初始化(例如放在主屏幕上)或 updatePeriodMillis 过期时执行。如果你想通过点击小部件来执行服务,你必须像这样“附加”一个待处理的意图:

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final Intent intent = new Intent(context, UpdateService.class);
PendingIntent pendingIntent = PendingIntent.getService(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....);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
for(int i=0,n=appWidgetIds.length;i<n;i++){
    int appWidgetId = appWidgetIds[i];
    appWidgetManager.updateAppWidget(appWidgetId , views);
}

(工作小部件的清理版本)。

关键是,onUpdate() 方法确实很少执行。与小部件的真正交互是通过待定意图指定的。

于 2011-02-24T20:20:31.110 回答
0

您可能想考虑不为您正在做的事情使用服务。如果它只是每天运行一次 updateViews(),那么请考虑在链接到您的 appwidget 的 XML 文件中将 android:updatePeriodMillis 设置为 86400000。您的 XML 文件看起来像这样:

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
  android:minWidth="72dp"
  android:maxWidth="72dp"
  android:updatePeriodMillis="86400000" >
</appwidget-provider>

这将使android每天更新一次您的appwidget,而不会在后台运行可能被用户正在运行的任务杀手杀死的服务,然后阻止您的小部件更新。请注意,如果您需要它以比每 30 分钟更快的速度更新,那么 android:updatePeriodMillis 将无法工作(最小值为 30 分钟),此时我建议使用 AlarmManager,因为这样会消耗更少的电池一个服务,也不会被任务杀手杀死。

于 2011-02-24T16:47:19.817 回答