【问题标题】:creating second counter in android eclipse在 android eclipse 中创建第二个计数器
【发布时间】:2015-02-08 13:09:02
【问题描述】:

我正在制作简单的 android 应用程序,它应该有从 60 秒到 0 秒的计数器。我有一个想法如何做到这一点,但我不确定这是否是最聪明的方法。而且我不确定如何使它在代码中工作。

想法: 在 .xml 文件中,我添加了 textView。我将创建扩展 Service 的 MyService 类,该类将由 OnCreate 函数内的 .java 文件调用(因为我希望立即开始计数)。 MyService 将每秒更改 textView 的内容(我将拥有每秒减少的 int 计数器,然后更改 textView 的文本)。

有没有更好的办法?

这是 MyService 类:

  public class MyService extends Service {

        //for timer:
        int counter = 0;

        static final int UPDATE_INTERVAL = 1000;
        private Timer timer = new Timer();

        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }


        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            doSomethingRepeatedly();
            return START_STICKY;
        }


        private void doSomethingRepeatedly() {
            timer.scheduleAtFixedRate( new TimerTask() {
                public void run() {

                 //code for changing the content

                }
            }, 0, UPDATE_INTERVAL);
        }

        @Override
        public void onDestroy() {
            super.onDestroy();

            //za timer
            if (timer != null){
                timer.cancel();

            }
        }
    }

我必须将此代码放在单独的 .java 文件中吗?

我不确定如何编写代码来更改 textView 的内容,因为我不确定是否可以调用 textView 的 id,因为它在单独的文件中?

这些是启动服务的函数:

 public void startService(View view) {
        startService(new Intent(getBaseContext(), MyService.class));
 }

  public void stopService(View view) {
        stopService(new Intent(getBaseContext(), MyService.class));
    }

我必须把它们放在哪里?

【问题讨论】:

标签: java android eclipse


【解决方案1】:

使用CountDownTimer

将倒计时安排到未来的某个时间,定期 沿途的间隔通知。显示 30 的示例 文本字段中的第二个倒计时:

 new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();

对 onTick(long) 的调用被同步到这个对象,这样一个 在上一个回调之前不会发生对 onTick(long) 的调用 完全的。这仅在执行时相关 onTick(long) 需要花费大量时间来执行,这很重要 与倒计时间隔相比。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-15
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多