【发布时间】:2011-11-16 18:03:07
【问题描述】:
我遵循了一堆教程,在谷歌上搜索和堆栈溢出,并想出了这个代码来更新我的小部件,当我触摸它时:
public class WidgetService extends Service{
@Override
public void onStart(Intent intent, int startId) {
Log.i("WidgetService", "Called");
String fakeUpdate = null;
Random random = new Random();
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this
.getApplicationContext());
int[] appWidgetIds = intent
.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
if (appWidgetIds.length > 0) {
for (int widgetId : appWidgetIds) {
int nextInt = random.nextInt(100);
fakeUpdate = "Random: " + String.valueOf(nextInt);
RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.widget);
remoteViews.setTextViewText(R.id.txt_updated, fakeUpdate);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
stopSelf();
}
super.onStart(intent, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
对于小部件提供者:
public class Widget extends AppWidgetProvider{
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget);
Intent intent = new Intent(context.getApplicationContext(),
WidgetService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getService(
context.getApplicationContext(), 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.cnt_widget, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
context.startService(intent);
}
}
在清单中:
<receiver
android:label="@string/next_trip_text"
android:name=".widget.Widget" >
<intent-filter >
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_info" />
</receiver>
还有xml:
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="272dp"
android:minHeight="72dp"
android:updatePeriodMillis="0"
android:initialLayout="@layout/widget"
android:configure="se.webevo.basttrafik.widget.WidgetConfigActivity" >
</appwidget-provider>
似乎根本没有调用该服务。有任何想法吗? :)
谢谢!
【问题讨论】:
-
您是否对清单文件进行了更改?添加接收器,意图过滤器?然后创建元数据文件,并以毫秒为单位提供更新时间??
-
是的,清单是正确的,添加了代码,请参阅编辑。
标签: android android-widget android-service