gpt4 book ai didi

java - 根据系统时间每30秒更新一次listView的正确方法

转载 作者:行者123 更新时间:2023-12-01 10:41:25 25 4
gpt4 key购买 nike

我目前正在尝试在 Android 应用程序中实现基于时间的双因素身份验证。该代码需要根据手机上的系统时间每 30 秒更新一次,例如。 21:13:00 和 21:13:30(时:分:秒)。我正在使用 Intent.ACTION_TIME_TICK 查看 BroadcastReceiver,但这只是每分钟一次。我的想法是使用它,然后在从 BroadcastReceiver 调用的方法内使用计时器。但是我不确定这是否是最好的方法,或者是否有其他方法可以让我每 30 秒获得一次 BroadcastReceiver 的效果。请记住,它遵循系统时间非常重要,否则代码可能会在服务器端过期。

目前我的代码如下,这是之前的答案 here

BroadcastReceiver _broadcastReceiver;
private final SimpleDateFormat _sdfWatchTime = new SimpleDateFormat("HH:mm");
private TextView _tvTime;

@Override
public void onStart() {
super.onStart();
_broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0)
_tvTime.setText(_sdfWatchTime.format(new Date()));
//Extra timer here, for the 30 second update..
}
};

registerReceiver(_broadcastReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

@Override
public void onStop() {
super.onStop();
if (_broadcastReceiver != null)
unregisterReceiver(_broadcastReceiver);
}

感谢您的宝贵时间。

最佳答案

使用广播接收器并不是理想的解决方案,该解决方案将比 B.Reciever 和 Intent 更准确,并且更容易编写/维护。

更好的方法是通过处理程序将延迟的可运行对象发布到 UI 线程的 Looper

static final private int DELAY_TIME = 30*1000;

private Runnable runnable = new Runnable() {
@Override
public void run() {
/* do what you need to do */
YOUR CODE HERE
/* post new handler to re-trigger in 30 seconds */
// wrap this in IF statement to make a way of stopping the looping.
handler.postDelayed(this, DELAY_TIME );
}
};

// create a handler that points to the UI Thread's Looper
private Handler handler = new Handler(Looper.getMainLooper());
// post the first runnable, that will start a cascading repeat set of runnables
handler.postDelayed(runnable, DELAY_TIME );

关于java - 根据系统时间每30秒更新一次listView的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34387152/

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