我希望我的应用程序始终以秒为单位更新时间并在其他活动中显示。我还需要时间和日期的数字来计算。谁能帮我?我试过这个,但它只记录一次,我想让它按时间更新。感谢。
package com.example.suntracking;
import java.util.Calendar;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
public class TimeClock extends Activity {
int timesec,timeminute,timehour,dateday,datemonth,dateyear,day,ampm;
String daytext,ampmtext;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Calendar c = Calendar.getInstance();
timesec = c.get(Calendar.SECOND);
timeminute = c.get(Calendar.MINUTE);
timehour = c.get(Calendar.HOUR);
ampm = c.get(Calendar.AM_PM);
if(ampm==0){
ampmtext="AM";
}else {
ampmtext="PM";
}
dateday = c.get(Calendar.DAY_OF_MONTH);
datemonth = c.get(Calendar.MONTH);
datemonth += 1;
dateyear = c.get(Calendar.YEAR);
day = c.get(Calendar.DAY_OF_WEEK);
switch(day){
case 1:
daytext="SUNDAY";
break;
case 2:
daytext="MONDAY";
break;
case 3:
daytext="TUESDAY";
break;
case 4:
daytext="WEDNESDAY";
break;
case 5:
daytext="THURSDAY";
break;
case 6:
daytext="FRIDAY";
break;
case 7:
daytext="SATURDAY";
break;
}
savePreferences();
Intent i= new Intent(TimeClock.this,MainActivity.class);
startActivity(i);
}
private void savePreferences() {
// TODO Auto-generated method stub
SharedPreferences savedata = getSharedPreferences("savealldata",0);
Editor editor=savedata.edit();
editor.putInt("timesec",timesec);
editor.putInt("timeminute", timeminute);
editor.putInt("timehour", timehour);
editor.putInt("dateday", dateday);
editor.putInt("datemonth", datemonth);
editor.putInt("dateyear", dateyear);
editor.putInt("ampm", ampm);
editor.putString("daytext", daytext);
editor.putString("ampmtext", ampmtext);
editor.commit();
}
}
答案 0 :(得分:0)
下载this演示项目。它包括使用具有适当滴答功能的Timer。忽略其余的Intent服务。
简而言之,这是代码:
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg != null && msg.what == 100) {
// Log.d(Constants.TAG, "What : " + msg.what);
changeTime();
}
super.handleMessage(msg);
}
};
// This is a timer just for ticking the clock after one second
Timer timer = new Timer(true);
timer.schedule(new TimerTask() {
@Override
public void run() {
// There are two ways to make handler work done one by posting a
// runnable or by handling the massages in onHandle method.
mHandler.sendEmptyMessage(100);
// or
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// changeTime();
// }
// });
}
}, 0, 1000);
private void changeTime() {
date.setTime(System.currentTimeMillis());
textView.setText("" + dateFormat.format(date));
}