在我的代码中添加一个计时器

时间:2010-11-25 12:25:33

标签: java android timer draw

我想添加一个计时器,在计时器的每个刻度线(1秒)上,使线条刷新。如何在我的代码中使用计时器?

以下是我的代码:

LineRefresh.java

package LineRefresh.xyz.com;

import java.util.Timer;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;

public class LineRefresh extends Activity {
DrawView drawView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    drawView = new DrawView(this);
    drawView.setBackgroundColor(Color.WHITE);
    setContentView(drawView);
}

}

DrawView.java

package LineRefresh.xyz.com;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class DrawView extends View {
Paint paint = new Paint();

public DrawView(Context context) {
    super(context);

}

@Override
public void onDraw(Canvas canvas) {
 paint.setColor(Color.BLACK);
    canvas.drawLine(50, 200, 270, 200, paint);
}

}

4 个答案:

答案 0 :(得分:3)

另一种方法是:

Handler updateHandler;

@Override
public void onCreateBundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  updateHandler = new Handler();
  // Do this first after 1 second
  updateHandler.postDelayed(RecurringTask, 1000);
}

Runnable RecurringTask = new Runnable() {
  public void run() {
    // Do whatever you want

    // Call this method again every 30 seconds
    updateHandler.postDelayed(this, 30000);
  }
};

我在使用Timer / TimerTask解决方案编组UI线程时遇到了一些麻烦,所以这是另一个最终为我工作的问题!

答案 1 :(得分:2)

这里是Java Timertask的解决方案:

Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                hereYourMethod();
                }
            }
        };
        timer.schedule(task, 1000,1000);// (the task, when to start, when to repeat)

答案 2 :(得分:1)

另一种方法是使用Handler。

mHandler = new Handler(new Handler.Callback()
{
    @Override
    public boolean handleMessage(Message msg)
    {
        if(msg.what == REFRESH)
        {
            // TODO Refresh Code

            return true;
        }

        return false;
    }
});

mHandler.sendEmptyMessageDelayed(REFRESH, mMilliSecondsToRefresh);

然后当你希望它停止时(这也应该放在onStop()中,以便当你的应用程序不活动时它不会在后台继续):

mHandler.removeMessages(REFRESH);

答案 3 :(得分:-1)

你可以让线程休眠1秒钟:

Thread.sleep(1000); //1000 milliseconds = 1 second

如果您使用的是Swing,最好使用 Swing计时器http://download.oracle.com/javase/tutorial/uiswing/misc/timer.html

在您的情况下,也许您应该使用计时器http://download.oracle.com/javase/6/docs/api/javax/swing/Timer.html