2012-05-17 45 views
2

我一直在開發一個Android應用程序,我需要每小時執行一項任務。我使用下面的代碼是:如何每小時執行一項任務?

private static final long ALARM_PERIOD = 1000L; 

public static void initAlarmManager(Context context) { 

    Editor editor=PreferenceManager.getDefaultSharedPreferences(context).edit(); 
    editor.putBoolean(context.getString(R.string.terminate_key), true).commit(); 

    AlarmManager manager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE); 
    Intent i = new Intent(context, AlarmEventReceiver.class); 
    PendingIntent receiver = PendingIntent.getBroadcast(context, 0, i, 0); 
    manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
      SystemClock.elapsedRealtime(), ALARM_PERIOD, receiver); 
} 

它爲我,但我的客戶告訴我,該任務只能1次,並會無法正常工作1小時。我在哪裏犯了一個錯誤?請告訴我。謝謝。

+0

接受一些答案 – user1378730

回答

3

根據你的代碼,ALARM_PERIOD是1000L,作爲重複間隔。所以我懷疑鬧鐘會每隔1000毫秒設定一次。

如果您設置每小時重複間隔,則應該是3600000L。 並注意,如果手機重新啓動,除非您再次啓動,否則您的鬧鈴管理器將不再工作。

這裏是我的代碼:

private void setAlarmManager() { 
    Intent intent = new Intent(this, AlarmReceiver.class); 
    PendingIntent sender = PendingIntent.getBroadcast(this, 2, intent, 0); 
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); 
    long l = new Date().getTime(); 
    if (l < new Date().getTime()) { 
     l += 86400000; // start at next 24 hour 
    } 
    am.setRepeating(AlarmManager.RTC_WAKEUP, l, 86400000, sender); // 86400000 
} 
+0

對不起,我忘了修復它。我使用此值來測試我的設備,但對於客戶端,我發送了具有所需值的應用程序。這不是錯誤工作的原因。 – user1166635

+0

在我的代碼中我使用RTC_WAKEUP並且它正在工作。 – NyanLH

+0

我的代碼和你的代碼有什麼不同? – user1166635

1

相反Alram-經理的我推薦你使用Android-TimerTask

TimerTask類代表一個任務在指定時間運行。該任務可以運行一次或重複運行。它的完美適合您的要求。

+0

我想是不是好主意,因爲我的應用程序不會做了,然後執行任務,每隔1小時,即應用程序沒有活動。當用戶執行應用程序時,它只會執行計劃並且屏幕將被關閉。如果計時器任務在這種情況下工作? – user1166635

+0

即使您的屏幕很近,TimerTask也會運行。或者你正在服務中執行它。 – user370305

+0

謝謝,但爲什麼你推薦我使用TimerTask來代替AlarmManager? – user1166635

0

嘗試通過改變你的setRepeating()方法這樣

manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime(), SystemClock.elapsedRealtime()+(60*60*1000), receiver); 

OR

測試修改代碼這是重複的,每分鐘

manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,Calendar.getInstance().getTimeInMillis(), Calendar.getInstance().getTimeInMillis()+(1*60*1000), receiver); 
2

有你在應用程序代碼中的manifest.xml增加接收器標籤
<receiver android:name=".AlarmReceiver" android:process=":remote"/>

+0

是的AlarmReceiver是您的廣播接收器。對? – Dhrupal

+0

是的。但爲什麼我需要爲android:process添加「remote」? – user1166635

+0

您必須添加,因爲您正在應用程序的背景上運行該過程(使用alarmreceiver brocast接收器編寫的內容)。 – Dhrupal

相關問題