问题描述
我目前正在学习 Android 中的小部件.
I am currently learning about widgets in Android.
我想创建一个显示 SSID、RSSI(信号)级别的 WIFI 小部件.
I want to create a WIFI widget that will display the SSID, the RSSI (Signal) level.
但我也希望能够从我正在运行的计算通过 wifi 的声音质量的服务向它发送数据.
But I also want to be able to send it data from a service I am running that calculates the Quality of Sound over wifi.
这是我在阅读和快速教程后得到的:
Here is what I have after some reading and a quick tutorial:
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.
The above seems to work ok, it updates the SSID on the widget every 10 seconds.
但是,从我的服务中获取信息的最有效方法是什么?该服务将在我的小部件上定期更新已运行的信息?
However what is the most efficent way to get the information from my service that will be already running to update periodically on my widget?
还有比使用计时器和计时器任务更好的方法来更新小部件吗?(避免轮询)
Also is there a better approach to updating the the widget rather than using a timer and timertask? (Avoid polling)
更新
根据 Karan 的建议,我在我的服务中添加了以下代码:
As per Karan's suggestion I have added the following code in my Service:
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,有什么想法吗?
This gets run everytime the RSSI level changes but it still never updates the TextView on my widget, any ideas why?
编辑
搞定了,谢谢卡兰
推荐答案
您可以使用以下代码更新widget的数据:
You can use the following code to update the data of widget :
ComponentName thisWidget = new ComponentName( getContext(), <ProviderClass> );
AppWidgetManager.getInstance( getContext() ).updateAppWidget( thisWidget, rempoteViews );
这篇关于如何动态更新小部件(不等待 30 分钟调用 onUpdate)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)