按照本教程,我快速创建了一个简单的小部件,它在主屏幕上每秒显示和更新当前时间:
问题: 我想知道如何更改此代码,以便仅在发生特定事件时更新时间。例如:仅当 wifi 状态发生变化时才更新时间。
以下是(希望)相关的代码部分:
<!-- Broadcast Receiver -->
<receiver android:name=".WifiSSIDWidget" android:label="@string/app_name">
<intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/wifi_ssid_widget_provider" />
</receiver>
这是小部件类代码:
public class HelloWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTime(context, appWidgetManager), 1, 1000);
}
private class MyTime extends TimerTask {
RemoteViews remoteViews;
AppWidgetManager appWidgetManager;
ComponentName thisWidget;
DateFormat format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM, Locale.getDefault());
public MyTime(Context context, AppWidgetManager appWidgetManager) {
this.appWidgetManager = appWidgetManager;
remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
thisWidget = new ComponentName(context, HelloWidget.class);
}
@Override
public void run() {
remoteViews.setTextViewText(R.id.widget_textview, "TIME = " +format.format(new Date()));
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
}
}