我想在我的Android应用程序中创建默认时间段的计时器。 请帮帮我。我的应用程序正在计算课程的剩余时间。如果课程在上午8:00开始并在上午10:00结束,则当前时间为上午9:30时,计时器将显示30分钟。任何人都可以解决这个问题吗?
答案 0 :(得分:0)
您可以使用处理程序和joda时间来计算分钟数。首先是活动中的静态内部类。静态类可防止内存泄漏。该处理程序将每分钟运行一次。
编辑:传入活动将允许您在激活中调用其他非静态方法
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 {
.....
}
}
在build.gradle文件中使用Android Studio进行gradle构建:
dependencies {
compile 'joda-time:joda-time:2.4'
compile 'joda-time:joda-time:2.4'
compile 'joda-time:joda-time:2.2'
}