【问题标题】:Android appwidget service won't startAndroid appwidget 服务无法启动
【发布时间】:2011-02-24 14:15:41
【问题描述】:

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

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

【问题讨论】:

    标签: android android-widget android-appwidget android-service


    【解决方案1】:

    “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() 方法确实很少执行。与小部件的真正交互是通过待定意图指定的。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        您可能想考虑不为您正在做的事情使用服务。如果它只是每天运行一次 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,因为这样会消耗更少的电池一个服务,也不会被任务杀手杀死。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多