I'm new to Android, so every simple thing seems a mountain.
I'm realizing an app that (with a background receiver) listen to phone calls and do something: this works, ok. I tried to add a widget (updated from receiver) showing some status, but this doesn't work, widget is not updated.This is part of my widget: when it's launched it shows correct status.
public class BlacklistWidget extends AppWidgetProvider {
RemoteViews remote;
ComponentName provider;
Context context;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
// create the remote view
remote = new RemoteViews(context.getPackageName(), R.layout.widget);
provider = new ComponentName(context, BlacklistWidget.class);
this.context = context;
Resources r = context.getResources();
String[] usage_arr = r.getStringArray(R.array.pref_usage_array);
int usage = Prefs.getUsage();
Utils.Log("Widget onUpdate: " + usage);
// remote.setImageViewResource(R.id.icon_usage,
remote.setTextViewText(R.id.usage, usage_arr[usage]);
appWidgetManager.updateAppWidget(provider, remote);
}
}
When receiver changes the status of a static class, this method is invoked:
public static void setUsage(int usage) {
Usage = USAGE.values()[usage];
try {
Resources r = pcontext.getResources();
String[] usage_arr = r.getStringArray(R.array.pref_usage_array);
remoteViews.setTextViewText(R.id.usage, usage_arr[usage]);
Utils.Log("Widget updated with " + usage);
} catch (Exception e) {
e.printStackTrace();
}
}
As you can see, code used to update widget is the same contained in widget Update().
No exception is thrown and text send for update is correct.. but widget TextView remains the same.I开发者_如何学Gon manifest widget is defined as foolows:
<receiver android:name=".BlacklistWidget" android:label="@string/app_name">
<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>
What am I doing wrong?
Is there a better way to reach my goal? Thank you so much.What you're doing in setUsage
is insufficient to update a widget: you have to call updateAppWidget
AFTER you update the RemoteViews
instance. Where you call Utils.Log("Widget updated with " + usage);
you have to load up the entire RemoteViews
instance again, set ALL the appropriate properties (including the text view you actually want to update) and then call updateAppWidget
.
精彩评论