如何动态更新Widget(不等待30分钟才能调用onUpdate)?

时间:2010-05-28 13:34:06

标签: android widget dynamic

我目前正在学习Android中的小部件。

我想创建一个WIFI小部件,它将显示SSID,即RSSI(信号)级别。

但我也希望能够从我正在运行的服务中发送数据,通过wifi计算音质。

以下是我阅读和快速教程后的内容:


public class WlanWidget extends AppWidgetProvider{

RemoteViews remoteViews;
AppWidgetManager appWidgetManager;
ComponentName thisWidget;
WifiManager wifiManager;

public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new WlanTimer(context, appWidgetManager), 1, 10000);

}


private class WlanTimer extends TimerTask{

        RemoteViews remoteViews;
        AppWidgetManager appWidgetManager;
        ComponentName thisWidget;


public WlanTimer(Context context, AppWidgetManager appWidgetManager) {

        this.appWidgetManager = appWidgetManager;
        remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
        thisWidget = new ComponentName(context, WlanWidget.class);
        wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);


}

@Override
public void run() {

        remoteViews.setTextViewText(R.id.widget_textview,
        wifiManager.getConnectionInfo().getSSID());
        appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}

}

以上似乎工作正常,它每10秒更新一次小部件上的SSID。

然而,从我的服务中获取信息的最有效方法是什么?这些信息已经在我的小部件上定期更新?

还有更好的方法来更新小部件而不是使用计时器和timertask吗? (避免投票)

更新

根据Karan的建议,我在我的服务中添加了以下代码:


RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
ComponentName thisWidget = new ComponentName( context, WlanWidget.class );
remoteViews.setTextViewText(R.id.widget_QCLevel, " " + qcPercentage);
AppWidgetManager.getInstance( context ).updateAppWidget( thisWidget, remoteViews );

这会在每次RSSI级别更改时运行,但它仍然永远不会更新我的小部件上的TextView,任何想法为什么?

修改

得到它的工作,谢谢Karan

2 个答案:

答案 0 :(得分:24)

您可以使用以下代码更新小部件的数据:

ComponentName thisWidget = new ComponentName( getContext(), <ProviderClass> );
AppWidgetManager.getInstance( getContext() ).updateAppWidget( thisWidget, rempoteViews );

答案 1 :(得分:2)

如果查看documentation about widgets,您应该可以设置2次更新之间的时间:

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="294dp"
android:minHeight="72dp"
android:updatePeriodMillis="86400000"
android:initialLayout="@layout/example_appwidget"
android:configure="com.example.android.ExampleAppWidgetConfigure" >

有了这个,你应该可以放任何你想要的时间吗? (它提到更新可能不会在您调用之后直接发生,因此请尽可能频繁地进行更新,但您必须处理电池)