2014-03-06 120 views
1

我想在Android中創建一個鬧鐘(AlarmManager)。 警報必須顯示剩餘時間,直到完成。顯示「剩餘時間」,直到鬧鐘開始

因此,用戶點擊「在11點設置鬧鐘」,並在TextView中看到「以xy小時/分鐘/秒鐘報警」。

我該如何做到這一點?

謝謝。

+1

這個 – Sonali8890

+0

可以與結束時間,像晚上11點倒計時工作中使用倒計時? – user1878413

+0

是的,它會。嘗試一下 – Sonali8890

回答

3

嘗試這樣

Calendar calendar = Calendar.getInstance(); 
    Long preTime = calendar.getTimeInMillis(); 

    // set alarm after 5 minute 

    calendar.add(Calendar.MINUTE, 5); 
    Long postTime = calendar.getTimeInMillis(); 
    Long delay = postTime - preTime; 

    AlarmManager manager = (AlarmManager)  getSystemService(Context.ALARM_SERVICE); 
    manager.set(AlarmManager.RTC_WAKEUP, postTime, null); 

    CountDownTimer timer = new CountDownTimer(delay, 1) { 

     @Override 
     public void onTick(long millisUntilFinished) { 
      final int seconds = (int) (millisUntilFinished/1000) % 60; 
      final int minutes = (int) ((millisUntilFinished/(1000 * 60)) % 60); 

      runOnUiThread(new Runnable() { 

       @Override 
       public void run() { 
        text.setText("minute " + minutes + " Second " + seconds); 
       } 
      }); 
     } 

     @Override 
     public void onFinish() { 
      // TODO Auto-generated method stub 

     } 
    }; 
    timer.start(); 
1
//INIT 
Calendar c = Calendar.getInstance(); 
int hNow = c.get(Calendar.HOUR_OF_DAY); //get the Hour 
int mNow = c.get(Calendar.MINUTE);   //get the Minute 

int hAlarm = 8;  //your alarm Hour 
int mAlarm = 30;  //your alarm Minute 

//FUNCTION 

int timeLeft = (hAlarm * 60 + mAlarm) - (hNow * 60 + mNow); 
if(timeLeft < 0) 
    timeLeft = 1440 + timeLeft; 
int hLeft = timeLeft/60;  //this is the hours left 
int mLeft = timeLeft % 60;  //this is the minutes left 
+0

對你的代碼的簡要解釋對於未來幫助其他用戶會有很大的幫助 – Brody