基于此tutorial我创建了自己的小部件的修改版本。问题是,现在AlarmManager.setRepeating没有按间隔触发intent。在我看来,Reciever甚至没有收到那份意图。
更确切地说,我有
WidgetActivity正确触发WidgetUpdate类,其中我有AlarmManager,当窗口小部件处于活动屏幕时,必须以间隔(30秒)与BroadcastReceiver通信。
WidgetUpdate.class
public class WidgetUpdate extends IntentService{
public WidgetUpdate() {
super(null);
}
public static int UPDATE_FREQUENCY_SEC = 30;
@Override
public void onCreate() {
super.onCreate();
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = alarmIntent();
long timeToRefresh = SystemClock.elapsedRealtime() + UPDATE_FREQUENCY_SEC * 1000;
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
timeToRefresh,
UPDATE_FREQUENCY_SEC * 1000,
alarmIntent);
}
private PendingIntent alarmIntent() {
Intent intentToFire = new Intent(WidgetAlarmReceiver.ACTION_REFRESH_ALARM);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0);
return alarmIntent;
}
@Override
protected void onHandleIntent(Intent intent) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (!pm.isScreenOn()) {
cancel();
}
else {
WidgetActivity widget = new WidgetActivity();
widget.updateWidget(getBaseContext());
}
}
WidgetAlarmReceiver.class
public class WidgetAlarmReceiver extends BroadcastReceiver{
public static final String ACTION_REFRESH_ALARM =
"WidgetAlarmReceiver.ACTION_REFRESH_ALARM";
@Override
public void onReceive(Context context, Intent intent) {
WidgetActivity.startWidgetUpdateService(context);
}
}
BroadcastReceiver无法启动该更新服务,我不确定原因。
编辑:在清单中:
<receiver android:name="WidgetAlarmReceiver">
<intent-filter>
<action android:name="WidgetAlarmReceiver.ACTION_REFRESH_ALARM" />
</intent-filter>
</receiver>