2011-12-09 75 views
2

我正在为Android开发动态壁纸。要在设定的时间刷新墙纸,我使用AlarmManager。大多数情况下,这个工作很好,但偶尔我的警报没有收到。最重要的是,我无法复制这种行为,它只是随机发生。我已经遇到了这个至少使用3个ROM。AlarmManager偶尔不会触发闹钟

现在的代码。
我用这个的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); 

,时间以毫秒为单位的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减零时“迷失”了。

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

+0

是否使用广播接收器类? –

+0

是的,请参阅第三个代码块。 – Thomas

+0

如果我取消现有的闹钟并用新的时间重新创建闹钟,我也会发生同样的情况。它在adb上显示剩余的正确时间,但一旦达到0就没有任何反应。 – draksia

回答

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) - 如果手机内的牛仔裤口袋深睡,用户不感兴趣的动态壁纸的变化 - 无需浪费电池汁并唤醒电话

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

+0

这不是我正在寻找的东西:刷新间隔每次都不一样,而且我还没有(关心)电池寿命(如果我是用RTC替换RTC_WAKEUP)。也许你可以指出我的代码中存在错误或AlarmManager中存在错误? – Thomas

+0

你在哪里激活这个意图? –

+0

'WallpaperService.WallpeperEngine.onCreate()'中的第一个。当前一个被触发时,下一个报警被设置,等等。 – Thomas