仅获取当前时间并在 android 内更新

Get current time only and update it in android

我只需要获取 HH:mm 格式(例如 14:20)的当前时间(没有数据),然后每秒或每分钟更新一次。我有点明白这段代码,但是否可以将其转换为字符串? 我需要在单独的 public 字符串中传递值 "time"。 任何解决方案? 谢谢

public class ClockCounter extends TimerTask {

public long time = System.currentTimeMillis();

@Override
public void run(){
    time += 1000; //add 1 second to the time
    //convert ms time to viewable time and set MainActivity.text (textview) text to this.
}

public long getTime(){ return time; }
}

更新:让它与每秒运行的服务一起工作。

你只需要有一个final变量SimpleDateFormat

final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");

并且您可以使用此代码在任何您想要的地方获取时间格式:

String time = dateFormat.format(new Date());

你可以这样做:

private void clock() {
  final Handler hander = new Handler();
  new Thread(new Runnable() {
     @Override
     public void run() {
        try {
           Thread.sleep(1000);
        } catch (InterruptedException e) {
           e.printStackTrace();
        }
        hander.post(new Runnable() {
           @Override
           public void run() {
              getTime();
              clock();
           }
        });
     }
  }).start();
}

void getTime() {
   SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss", Local.getDefault());
   textview.setText(dateFormat.format(new Date()));
}

您可以使用下面的代码获取带有小时、分钟和秒的当前时钟

final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String time = dateFormat.format(new Date());

使用 liveData 和协程:

 val currentTime = liveData {
        while (true){
            emit(Calendar.getInstance().time)
            kotlinx.coroutines.delay(1000)
        }
    }