Таймер Android, java работает только один раз

#java #android #timer

#java #Android #таймер

Вопрос:

Я пытаюсь создать таймер, чтобы добавлять к переменной 1 каждые 2 секунды. Итак, я использую Java timer, но проблема в том, что он работает только в первый раз, то есть он добавляет только 1 к переменной.

Вот код:

 private Ball[] arr ; // ball array
private int ballNum; // the number of the balls on the screen
private float radius; // the radius of the balls
private int count;// count if to sleep or not
private Timer timer;

public BallCollection(int ballNum) {
    this.arr = new Ball [ballNum];
    this.ballNum = ballNum;
    this.radius = 50;
    this.count = 0;

    timer = new Timer();
    timer.scheduleAtFixedRate(new PachuTask(), 0, 2000);

    for(int i = 0; i < arr.length; i  )
        this.arr[i] = new Ball(this.radius);
}

private boolean isBumpWithRest(Ball[] few, Ball one) {
    for(int i =0;i < this.arr.length; i  ) {
        if(this.arr[i] != one)
            if(this.arr[i].isBump(one))
                return true;
    }
    return false;
}

public void setBalls(Canvas canvas) {
    Random rnd = new Random();
    for(int i = 0; i < this.ballNum; i  ) {
        int x = (int) (rnd.nextInt((int)(canvas.getWidth() - 4 * this.radius))   2 * this.radius);
        int y = (int) (rnd.nextInt((int)(canvas.getHeight() - 4 * this.radius))   2 * this.radius);

        this.arr[i].setX(x);
        this.arr[i].setY(y);
        while(this.isBumpWithRest(this.arr, this.arr[i]) amp;amp; arr[i].getX() != 0) {
            x = (int) (rnd.nextInt((int)(canvas.getWidth() - 2 * this.radius))   this.radius);
            y = (int) (rnd.nextInt((int)(canvas.getHeight() - 2 * this.radius))   this.radius);
            this.arr[i].setX(x);
            this.arr[i].setY(y);
        }
    }
}
public void draw(Canvas canvas) {
    Paint p = new Paint();
    p.setColor(Color.RED);
    p.setTextSize(50);
    for (int i = 0; i < this.count; i  ) {
        arr[i].draw(canvas, p);
        canvas.drawText(""   this.count, 100, 100, p);
    }
}

class PachuTask extends TimerTask {
    public void run() {
        if(count < arr.length   1)
            count  ;    
    }
  }
  

Комментарии:

1. Может быть, потому, что он не вводит if условие в TimerTask ?

2. это не так, потому что я также пытался сделать (если count < 100), и переменная count всегда остается равной 1.

3. Вы пытались установить в нем точку останова if и проверять, достигает ли она ее каждые 2 секунды?

4. Ммм, я действительно не знаю, потому что мой друг рассказал мне, как это сделать, но он сказал, что он вызывает метод запуска после того, как таймер достигнет 2 секунд

5. Я думаю, это предположительно так. Вам следует научиться пользоваться отладчиком. В этой ситуации вам действительно могло бы помочь проверить, действительно ли он вводит run метод каждые 2 секунды. Какую IDE вы используете? Конечно, есть несколько хороших руководств, которые научат вас отлаживать вашу программу.

Ответ №1:

Попробуйте добиться этого с помощью обработчиков, он будет вызывать каждые 2 секунды сам

 Runnable runnable1 ,runnable2 = null ;
final Handler handler1 = new Handler();
        final Handler handler2 = new Handler();

        runnable2 = new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                handler1.postAtTime(runnable1, 0);
            }
        };
        runnable1 = new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                System.err.println("Called in two second");
                handler2.postDelayed(runnable2, 2000);
            }
        };


        handler1.postDelayed(runnable1, 0);
  

Комментарии:

1. Хммм, не могли бы вы показать мне, как использовать это в моем коде? Я не понимаю, как.

2. count = count 1; будет в методе runnable2

Ответ №2:

Попробуйте использовать этот код

 private Ball[] arr; // ball array
private int ballNum; // the number of the balls on the screen
private float radius; // the radius of the balls
private int count;// count if to sleep or not
private Timer timer;

public BallCollection(int ballNum) {

    //check the value of ballNum here.

    this.arr = new Ball[ballNum];
    this.ballNum = ballNum;
    this.radius = 50;
    this.count = 0;

    for (int i = 0; i < arr.length; i  ) {
        this.arr[i] = new Ball(this.radius);
    }
    //check the array size of arr here.
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            //if (count < arr.length   1) {
            count = count   1;
            //}
            System.out.println(""   count);
        }
    }, 0, 2000);
}

private boolean isBumpWithRest(Ball[] few, Ball one) {
    for (int i = 0; i < this.arr.length; i  ) {
        if (this.arr[i] != one) {
            if (this.arr[i].isBump(one)) {
                return true;
            }
        }
    }
    return false;
}

public void setBalls(Canvas canvas) {
    Random rnd = new Random();
    for (int i = 0; i < this.ballNum; i  ) {
        int x = (int) (rnd.nextInt((int) (canvas.getWidth() - 4 * this.radius))   2 * this.radius);
        int y = (int) (rnd.nextInt((int) (canvas.getHeight() - 4 * this.radius))   2 * this.radius);

        this.arr[i].setX(x);
        this.arr[i].setY(y);
        while (this.isBumpWithRest(this.arr, this.arr[i]) amp;amp; arr[i].getX() != 0) {
            x = (int) (rnd.nextInt((int) (canvas.getWidth() - 2 * this.radius))   this.radius);
            y = (int) (rnd.nextInt((int) (canvas.getHeight() - 2 * this.radius))   this.radius);
            this.arr[i].setX(x);
            this.arr[i].setY(y);
        }
    }
}

public void draw(Canvas canvas) {
    Paint p = new Paint();
    p.setColor(Color.RED);
    p.setTextSize(50);
    for (int i = 0; i < this.count; i  ) {
        arr[i].draw(canvas, p);
        canvas.drawText(""   this.count, 100, 100, p);


    }
}
  

И вам не нужно создавать (расширять) PachuTask класс

Пожалуйста, измените его в соответствии с вашими потребностями

Комментарии:

1. Ммм, это не работает, значение переменной счетчика остается равным 0.

2. проверьте, равно ли значение ballNum 1

3. значение равно 2, пробовал изменять его до 10, 50, 100 каждый раз с одним и тем же результатом.

4. @user3674127 проверьте, полностью ли инициализирован ваш массив, я снова изменил код