2015-12-07 19 views
0

我想在我的android應用程序中爲默認時間段創建一個計時器。 請幫我。我的應用程序正在計算一個班級的剩餘時間。如果課程在上午8:00開始,上午10:00結束,並且當前時間爲上午9:30時,計時器將顯示30分鐘。有誰能解決這個問題嗎?在android中添加默認計時器

+1

所以基本上你需要不斷更新用戶界面,對嗎? – himanshu1496

回答

0

您可以使用處理程序和joda時間來計算您的分鐘數。首先是活動中的靜態內部類。靜態類可防止內存泄漏。該處理程序將每分鐘運行一次。

編輯:在活動傳遞將允許您調用其他非靜態方法在activty

public static class TimeLeftHandler extends Handler { 
    private String startTime; 
    private String endTime; 
    private WeakReference<MyActivity> activity 

    public TimeLeftHandler(MyActivity activity, String startTime, String endTime) { 
     this.startTime = startTime; 
     this.endTime = endTime; 
     this.activity = new WeakReference<MyActivity>(activity); 
    } 

    @Override 
    public void handleMessage(Message msg) { 
     Log.d("Timeout", "Timeout thrown from SubjectSelection"); 
     DateTime now = new DateTime(); 
     DateTimeFormatter format = DateTimeFormat.forPattern("HH:mm"); 
     LocalTime classStartTime = format.parseLocalTime(startTime); 
     LocalTime classEndTime = format.parseLocalTime(endTime); 
     DateTime nowRoundFormat = new DateTime().dayOfMonth().roundFloorCopy(); 
     DateTime classStart = nowRoundFormat.plusHours(classStartTime.getHourOfDay()).plusMinutes(classStartTime.getMinuteOfHour()); 
     DateTime classEnd = nowRoundFormat.plusHours(classEndTime.getHourOfDay()).plusMinutes(classEndTime.getMinuteOfHour()); 

     if (now.isAfter(classStart) && now.isBefore(classEnd)) { 

      myMinutesTextView.setText("There are " + Minutes.minutesBetween(now, classEnd)); 
     } 

     //call non-static method. 
     activity.get().nonstaticMethod(); 

     sendEmptyMessageDelayed(0,60000); 


    } 

那麼活動:

public class MyActivity extends Activity { 
    private TextView myMinutesTextView; 
    private TimeLeftHandler timeLeftHandler; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.mylayout); 

     myMinutesTextView = (TextView) findViewById(R.id.mytextview); 
     timeLeftHandler = new TimeLeftHandler("08:00", "10:00"); 
    } 

    @Override 
    protected void onStart() { 
     //start the handler 
     timeLeftHandler.sendEmptyMessage(0); 

    } 

    @Override 
    protected void onDestroy() { 
     //clean up. 
     timeLeftHandler.removeMessages(0); 



    } 

    private void nonstaticMethod() { 
     //Your code. 
    } 

    public static class TimeLeftHandler extends Handler { 
     ..... 
    } 


} 

對於Android Studio中的gradle這個構建你的build.gradle文件:

dependencies { 
    compile 'joda-time:joda-time:2.4' 
    compile 'joda-time:joda-time:2.4' 
    compile 'joda-time:joda-time:2.2' 
} 
+0

我看到你正在將Activity傳遞給你的處理程序構造函數,但從未使用它。爲什麼要這麼做? – k0sh

+0

@ k0sh如果你想調用活動中的其他任何東西,你需要一種方法來調用靜態類中的非靜態例程。 –

+0

是的,但是在您的示例代碼中,您從未使用過它。因爲相信我,這裏的一些人只會複製和粘貼你的代碼,而不知道它的用法。 – k0sh