gpt4 book ai didi

android - 连续获取当前时间android

转载 作者:行者123 更新时间:2023-11-29 00:18:58 25 4
gpt4 key购买 nike

我正在尝试为 android 制作一个闹钟应用程序,我应该做的第一件事就是不断获取系统的当前时间,所以我这样做了,但它只获取了当前的秒数,没有更多,有帮助吗?这是代码:

public class MainActivity extends Activity {
public Button time;
public TextView secondview;
public static int hours, mins, secs;

Handler main;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = (Button) findViewById(R.id.button1);
secondview = (TextView) findViewById(R.id.textView2);

new Thread(new Runnable() {

@Override
public void run() {
secondview.setText(String.valueOf(secs));
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();

main = new Handler() {

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);

Calendar mycal = Calendar.getInstance();
hours = mycal.get(Calendar.HOUR);
mins = mycal.get(Calendar.MINUTE);
secs = mycal.get(Calendar.SECOND);

secondview.setText(String.valueOf(secs));
}
};
}
}

最佳答案

HandlerThread 是这类问题的糟糕选择。

要制作闹钟应用,请使用 AlarmManager .

您应该仔细选择要使用的计时器类型。 (ELAPSED_REALTIMERTC,....)
对于闹钟应用,RTC_WAKEUP 是不错的选择。

Android developer site has training如何使用 AlarmManager

引用:

// Set the alarm to start at approximately 2:00 p.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 14);

// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);

还有一些用例的例子。

关于android - 连续获取当前时间android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24345394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com