2016-08-06 75 views
-2

我想在系統時間戳達到特定時間時調用函數。 反正比CountDownTimer更好嗎? 它應該在服務上調用,因爲我希望它在應用程序關閉時仍然運行。在特定時間戳調用函數的最佳方法

非常感謝。

+0

您可以嘗試使用警報管理器,通過此設置您可以設置特定的時間戳單個或重複出現以運行服務。 – kabuto178

回答

0

你必須使用BroadcastReceiver和AlarmManager一樣。

//Create alarm manager 
AlarmManager malarmMngr = (AlarmManager)getSystemService(Context.ALARM_SERVICE); 

//Create pending intent & register it to your alarm notifier class 
Intent intent = new Intent(this, yourBroadcastReceiver.class); 
PendingIntent mPendInt = PendingIntent.getBroadcast(this, 0, intent, 0); 

//set your time stamp (for once in future) 
malarmMngr .set(AlarmManager.RTC_WAKEUP, yourtimestamp, mPendInt); 

現在創建yourBroadcastReceiver類來調用函數。

public class yourBroadcastReceiver extends BroadcastReceiver { 
    public MyReceiver() { 
    } 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // This method is called when this BroadcastReceiver receives an Intent broadcast. 
     // Call your function here 
    } 
} 
+0

難道你不想alarmManager.setExact()? – CodeCody

相關問題