【问题标题】:How to detect change in time each second in Android?如何在Android中检测每秒的时间变化?
【发布时间】:2015-03-04 06:19:35
【问题描述】:

我正在通过关注this tutorial 为 android 创建自定义表盘。我已经实现了广播接收器来检测时间变化,如下所示:

在我的活动中,我有静态块来过滤以下意图:

static {
    intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
    intentFilter.addAction(Intent.ACTION_TIME_TICK);
    intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
 }

我的接收器类:

public class MyReciever extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        c = Calendar.getInstance();
        Log.d("myapp", "time changed");
        hrs = c.get(Calendar.HOUR_OF_DAY);
        min = c.get(Calendar.MINUTE);
        sec = c.get(Calendar.SECOND);

        txt_hrs.setText(String.valueOf(hrs));
        txt_mins.setText(String.valueOf(min));
        txt_sec.setText(String.valueOf(sec));
    }
}

我已经在 oncreate() 中注册了接收者:

 MyReciever myReciever = new MyReciever();
registerReceiver(myReciever,intentFilter);

上面的代码在几小时和几分钟内都可以正常工作,但在几秒钟内就不行了。

Intent.ACTION_TIME_TICK 的问题在于它是每分钟广播一次,而不是每秒钟广播一次。

我需要检测表盘上时钟每秒的时间变化。任何人都有“检测每秒时间变化”的解决方案吗?

【问题讨论】:

    标签: android android-intent wear-os android-broadcast watch-face-api


    【解决方案1】:

    你可能看起来why you are not getting intent after every seconds。所以更好的是创建一个单独的线程或使用 asynctask ,您需要每秒钟更新一次 textview。


    或者您可以使用TimerTimerTask 来实现此目的,如下所示

    public void updateTimeOnEachSecond() {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
    
        @Override
        public void run() {
            c = Calendar.getInstance();
            Log.d("myapp", "time changed");
            hrs = c.get(Calendar.HOUR_OF_DAY);
            min = c.get(Calendar.MINUTE);
            sec = c.get(Calendar.SECOND);
    
           runOnUiThread(new Runnable() {
            @Override
            public void run() {
            txt_hrs.setText(String.valueOf(hrs));
            txt_mins.setText(String.valueOf(min));
            txt_sec.setText(String.valueOf(sec));
           }
        });
    
        }
    }, 0, 1000);
    

    }

    并在从活动中初始化每个视图后调用此方法。

    【讨论】:

    • 它可以工作,但你的代码有一个小的变化。您应该将 setText 方法放在 runOnUiThread 中,否则会抛出 CalledFromWrongThreadException: 只有创建视图层次结构的原始线程才能接触其视图。我已经编辑了代码。请批准该编辑。
    • @Krupal 嘿,谢谢。是的,我错过了。 :) 继续……更新
    猜你喜欢
    • 1970-01-01
    • 2021-08-10
    • 2011-01-16
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多