2011-12-09 74 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