java - 在 android eclipse 中创建第二个计数器

标签 java android eclipse

我正在制作简单的 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));
    }

我必须把它们放在哪里?

最佳答案

使用 CountDownTimer .

Schedule a countdown until a time in the future, with regular notifications on intervals along the way. Example of showing a 30 second countdown in a text field:

 new CountDownTimer(30000, 1000) {

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

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

The calls to onTick(long) are synchronized to this object so that one call to onTick(long) won't ever occur before the previous callback is complete. This is only relevant when the implementation of onTick(long) takes an amount of time to execute that is significant compared to the countdown interval.

关于java - 在 android eclipse 中创建第二个计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28394262/

相关文章:

android - 文本域对齐输入文本中心

android - 在平板电脑上强制关闭和 android.view.InflateException

java - MCRYPT_RIJNDAEL_256 Java 中的 PHP 加密

java - 为什么此代码在使用 == 时会失败,但使用 <= 时却可以?

java - 如何在Hybris中删除表的所有记录?

java - Okhttp javax.net.ssl.sslexception : connection closed by peer

android - Theta V wifi api 不一致

java - 将 TextView 与 EditText 对齐

android - 如何快速添加新项目到 ListView

java - Eclipse 控制台打印文字不正确