use*_*637 7 android android-widget alarmmanager android-service android-alarms
我的应用程序有一个显示今天日期的小部件,需要在午夜更新.窗口小部件在清单中定义为
<manifest>
...
<application>
...
<receiver
android:name=".MyWidgetProviderClass"
android:label="MyLabel" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_icon_info" />
</receiver>
</application>
</manifest>
Run Code Online (Sandbox Code Playgroud)
小部件信息文件是
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/my_layout"
android:minHeight="40dp"
android:minWidth="294dp"
android:updatePeriodMillis="3600000" >
</appwidget-provider>
Run Code Online (Sandbox Code Playgroud)
这会导致小部件在午夜和下午1点之间的任何时间更新,但我想更新到更接近午夜,所以我在应用程序中添加了一个意图接收器
<receiver
android:name=".MyWidgetUpdaterClass"
android:enabled="true" >
<intent-filter>
<action android:name="MyAction" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
和静态方法
public static void setMidngintAlarms(Context context) {
Intent intent = new Intent("MyAction");
PendingIntent pendingIntent =
PendingIntent.getBroadcast(context, 0, intent, 0);
long interval = 24*60*60*1000;
long firstTime = SystemClock.elapsedRealtime() +
millisecondsToNextMidnight();
AlarmManager am = (AlarmManager)context.getSystemService(
Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, interval, pendingIntent);
}
Run Code Online (Sandbox Code Playgroud)
(因为警报管理器以相同的意图请求相互覆盖,所以多次调用setMidngintAlarms没有坏处).
我尝试从几个地方(从应用程序的主要活动,从AppWidgetProvider的onUpdate()等)调用setMidnightAlarms().一切运行良好,接收到警报管理器意图,并且只有应用程序运行时才更新窗口小部件.如果我杀了应用程序,小部件会在午夜停止更新.
知道如何让小部件在午夜更新吗?我需要添加服务吗?如果是这样的话?任何例子?
我有点惊讶的是,让这个基本功能起作用是多么微不足道.
我通过以下方式解决这个问题:
启动一个服务来监听Intent.ACTION_TIME_TICK消息。然后,如果时间已到,则向小部件发送广播。(每分钟)。
在小部件中接收广播并判断天气是否是午夜:
代码:
if (MyWidget.BROADCAST_TIME_TICK.equals(action)) {
//If it's midnight, then update.
int hour = Calendar.getInstance().get(Calendar.HOUR);
int minute = Calendar.getInstance().get(Calendar.MINUTE);
Utils.log(TAG, "time is : " + hour+":" + minute);
if (!(hour == 0 && minute == 0)) { //Only update at midnight's time tick.
return;
} else {
//Do the midnight stuff.
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1708 次 |
| 最近记录: |