Appwidgetmanager.updateAppwidget()没有做任何事情

时间:2012-04-18 17:14:34

标签: android widget android-appwidget

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

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

1 个答案:

答案 0 :(得分:0)

你如何获得m_appWidgetIds?

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

updateAppWidget (ComponentName provider, RemoteViews views) 

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

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