1

根据本教程,我创建了自己的小部件的修改版本。现在的问题是 AlarmManager.setRepeating 没有间隔触发意图。在我看来,接收者甚至没有收到那个意图。

更准确地说,我有

  • WidgetActivity 扩展 AppWidgetProvider
  • WidgetUpdate 扩展 IntentService
  • WidgetAlarmReceiver 扩展 BroadcastReceiver

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>
4

0 回答 0