2014-04-16 28 views
0

我一直在試圖弄清楚如何在android中獲取當前時間,並且我想知道當時鍾達到特定時間時如何運行一段代碼。最終我想做的是當時鍾是晚上9點30分。做一些事情或者運行一段代碼。我從來沒有在android或java上處理過。Android:獲取系統時間和安排任務

+0

您的應用程序將作爲服務運行,還是需要在@ 9:30開始? – Libin

回答

0

有多種方法可以得到當前時間的Android如

Date currentDate = new Date(System.currentTimeMillis()); 

關於在特定時間運行的代碼,請AlarmManager它允許您安排您的應用程序運行。

此外,檢查出Alarm Manager Example

0

有一些事情你需要使用AlarmManager時,尤其是當你的設備處於休眠狀態(獲得鎖,並保持它,直到你的任務完成)審議。我建議你閱讀that

0

試試這個:

得到如下的當前系統時間:

long currentTime = System.currentTimeMillis(); 

和下面的將來時間設置任務:

Calendar cal = Calendar.getInstance(); 
cal.add(Calendar.SECOND, 10); 
Intent serviceIntent = new Intent(this, GPSTrackerService.class); 
PendingIntent pintent = PendingIntent.getService(this, 0, serviceIntent, 0); 
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
//every 2 min 
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),timeSlice, pintent); 

更多介紹請參考以下鏈接:

How to set an alarm to fire properly at fixed time?

+0

我如何申請這個,我只想檢查時間是晚上9點30分? – JohnnyWineShirt

+0

請檢查這個http://stackoverflow.com/questions/2992882/how-to-set-an-alarm-to-fire-properly-at-fixed-time – MohdTausif