【问题标题】:How to display timer in activity?如何在活动中显示计时器?
【发布时间】:2010-11-11 02:09:11
【问题描述】:

我需要在应用程序中的一些活动上显示持续时间。计时器在其中一个 Activity 启动时启动。

  • 我应该为计时器使用服务吗?
  • 这是最好的方法吗?
  • 或者我应该从 Activity 之一启动线程?

【问题讨论】:

  • 让我稍微澄清一下这个问题:计时器应该可以跨多个活动访问。另一种完全不同的方法是存储开始时间,然后在每个活动中检查当前时间,减去开始时间,然后更新持续时间 gui。

标签: android timer android-activity


【解决方案1】:

我认为在您描述的用例中,最好存储时间戳(请参阅Data Storage)并计算用于 GUI 的增量。如果您需要在其中一个活动中显示实时时钟,您可以在该活动中创建一个单独的线程来更新时钟。

【讨论】:

    【解决方案2】:

    好吧,根据显示进度所需的界面工作量,我将在活动中启动一个线程,然后创建一个计时器来检查线程进度的状态并根据需要更新界面。服务适用于不需要大量界面通知/更新的后台任务。

    这是我目前正在处理的项目中的一个示例(UpdateListRunnable 只是在我的列表适配器上调用“notifyDataSetChanged()”。我在代码中多次执行此操作,因此我将其封装在一个类中。此外,updateHandler 只是一个普通的 Handler 实例):

    @Override
    public void run() {
        Timer updateProgressTimer = null;
        UpdateItem currentItem = null;
    
        for(int i = 0; i < items.size(); i++) {
            currentItemIndex = i;
            currentItem = items.get(i);
    
            if (currentItem.isSelected() == true) {
                updateProgressTimer = new Timer();
    
                updateProgressTimer.scheduleAtFixedRate(new TimerTask() {
                    @Override
                    public void run() {
                        updateHandler.post(new UpdateListRunnable());
                    }
                }, 0, 2000); // check every 2 seconds
    
                lookupDb.downloadUpdate(currentItem);
    
                currentItem.setUpToDate(true);
                currentItem.setStatusCode(UpdateItem.UP_TO_DATE);
                currentItem.setProgress(0);
                updateProgressTimer.cancel();
    
                updateHandler.post(new UpdateListRunnable());
            } // end if its the database we are hosting on our internal server
        } // end for loop through update items
    
        currentItemIndex = -1;
    } // end updateThread run
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多