Android应用小部件服务无法启动

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;
    }
}
3个回答

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()方法真的很少被执行。与小部件的实际交互是通过挂起意图来指定的。


2

你的Service可能没有在清单文件中注册。或者你的AppWidgetProvider没有在清单文件中注册。


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每天更新您的小部件,而无需在后台运行可能会被用户运行的任务杀手杀死的服务,从而停止您的小部件更新。只是一个注意事项,如果您需要它比每30分钟更新更快,则android:updatePeriodMillis不起作用(其最小值为30分钟),此时我建议使用AlarmManager,因为它会比Service使用更少的电池,并且也不会被任务杀手杀死。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接