3

我正在为 Android 开发动态壁纸。要在设定的时间刷新壁纸,我使用 AlarmManager。大多数时候这很好用,但偶尔我的警报没有收到。最重要的是,我无法复制这种行为,它只是随机发生的。我使用至少 3 个 ROM 遇到了这个问题。

现在是代码。
我使用这个 PendingIntent:

mRefreshIntent = new Intent()
    .setComponent(new ComponentName(mContext, RefreshBroadcastReceiver.class))
    .setAction("my.package.name.REFRESH_WALLPAPER");
mPendingRefreshIntent = PendingIntent.getBroadcast(
    mContext, 
    0, 
    mRefreshIntent, 
    PendingIntent.FLAG_CANCEL_CURRENT);

这是我设置闹钟的代码:

mAlarmManager.set(AlarmManager.RTC_WAKEUP, time, mPendingRefreshIntent);

其中 time 是以毫秒为单位的 UTC 时间。我经常使用 验证警报是否按预期设置adb shell dumpsys alarm,确实如此。

接收方:

public class RefreshBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("DayNight", "onReceive     ; " + System.currentTimeMillis());
        DayNightService.refresher.refresh();
        Log.d("DayNight", "onReceive done; " + System.currentTimeMillis());
    }
}

相关的清单行:

<application>
    ...
    <receiver
        android:name="RefreshBroadcastReceiver">
        <intent-filter>
            <action android:name="my.package.name.REFRESH_WALLPAPER" />
        </intent-filter>
    </receiver>
    ...
</application>

未触发的警报总是事先存在于队列中(dumpsys 警报),之后不在警报日志中。似乎他们在 T 减零时“迷路”了。

如果你们中的一个人能为我解决这个问题,我将非常高兴。

4

1 回答 1

2

我使用以下代码:

  Intent intent = new Intent(ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_NO_CREATE);
    Log.d(LOG_TAG, "pending intent: " + pendingIntent);
    // if no intent there, schedule it ASAP
    if (pendingIntent == null) {
        pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        // schedule new alarm in 15 minutes
        alarmService.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(),300000, pendingIntent);
        Log.d(LOG_TAG, "scheduled intent: " + pendingIntent);
    }

请注意,我要求不精确的重复警报和 RTC(不是 RTC_WAKEUP) - 如果手机在牛仔裤口袋深处睡觉,用户对动态壁纸的更改不感兴趣 - 无需浪费电池电量并唤醒手机

您可能还需要注册启动完成广播接收器以在重新启动时开始更新计划。

于 2011-12-09T15:11:54.430 回答