我创建了一个由服务更新的小部件。但是,该服务处理的其接口在添加时并未更新,而是在应用程序的第二次运行时更新。
小部件提供者.java:
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int appWidgetId : appWidgetIds) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widgetlayout);
Intent intent = new Intent(context, MetalPriceService.class);
intent.setAction(MetalPriceService.UPDATEPRICE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_refresh_btn, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
context.startService(intent);
}
小部件价格更新服务.java:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStart(intent, startId);
try {
updatePrice(intent); //deal with interface updating stuffs
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
stopSelf(startId);
return START_STICKY;
}