Android appwidget服务无法启动
作者:互联网
当我在调试模式下运行时,我似乎无法到达服务内部的任何断点,这是为什么呢?
@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;
}
}
解决方法:
仅在初始化小部件(例如放在主屏幕上)或updatePeriodMillis过期时才执行“ onUpdate”方法.如果您想执行服务,例如通过单击窗口小部件,您必须像这样“附加”挂起的意图:
@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()方法.通过挂起的意图指定与小部件的真正交互.
标签:android-appwidget,android-service,android-widget,android 来源: https://codeday.me/bug/20191102/1994784.html