我正在创建一个从数据库查询数据的应用程序小部件,并在此数据更改后使用内容观察器更新标签。问题是创建小部件时,我将标签更新为正确的值。当数据更改时,内容观察者会正确注册,但我无法更新小部件。代码如下所示:
//called after the configuration activity is done
public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId){
m_appWidgetManager = appWidgetManager;
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
m_account = prefs.getString("account" + appWidgetId, "unknown");
m_label = prefs.getString("label" + appWidgetId, "unknown");
m_context = context;
if (!m_accounts.contains(m_account)){
m_accounts.add(m_account);
m_context.getContentResolver().registerContentObserver(GmailContract.Labels.getLabelsUri(m_account), true,new MyContentObserver(new Handler()));
}
updateViews();
}
在 ContentObserver 中,我只覆盖了以下函数:
@Override
public void onChange(boolean selfChange) {
GmailUnreadCounterActivity.updateViews();
super.onChange(selfChange);
}
updateViews 函数看起来像这样(当从 updateAppWidget 调用时,它工作得很好,当从 contentobserver 调用时,小部件没有更新,尽管值发生了变化)
public static void updateViews(){
System.out.println("Number of widgets:" + m_appWidgetIds.length);
for (int i = 0; i < m_appWidgetIds.length; i++){
SharedPreferences prefs = m_context.getSharedPreferences(PREFS_NAME, 0);
m_account = prefs.getString("account" + m_appWidgetIds[i], "unknown");
m_label = prefs.getString("label" + m_appWidgetIds[i], "unknown");
Cursor c = m_context.getContentResolver().query(GmailContract.Labels.getLabelsUri(m_account),null,null,null,null);
while (c.moveToNext()) {
if (c.getString(c.getColumnIndex(GmailContract.Labels.CANONICAL_NAME)).equals(m_label)){
String line = String.valueOf(c.getInt(c.getColumnIndex(GmailContract.Labels.NUM_UNREAD_CONVERSATIONS)));
remoteViews = new RemoteViews(m_context.getPackageName(), R.layout.main);
remoteViews.setTextViewText(R.id.unread_count,
line);
AppWidgetManager.getInstance(m_context).updateAppWidget(m_appWidgetIds[i], remoteViews);
}
}
}
}