1

我正在创建一个从数据库查询数据的应用程序小部件,并在此数据更改后使用内容观察器更新标签。问题是创建小部件时,我将标签更新为正确的值。当数据更改时,内容观察者会正确注册,但我无法更新小部件。代码如下所示:

//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);
            }
        }
    }   
}
4

1 回答 1

0

你如何获得 m_appWidgetIds?

为什么要将其保留在 for 循环中并更新所有实例。而不是那种用途

updateAppWidget (ComponentName provider, RemoteViews views) 

这将更新小部件的所有实例。

使用以下代码获取 ComponentName ComponentName provider = new ComponentName(context, YourAppWidgetProvider.class);

于 2012-04-18T18:40:59.047 回答