0

我正在编写简单的代码来启动和停止TimerTask。在这段代码Stop中可以工作,但我无法重新启动TimerTask。请帮我解决这个问题。

我的代码:

public class MainActivity extends Activity implements View.OnClickListener {
    private TimerThread timerThread;
    private boolean timerHasStarted = false;
    private Button button;
    private TextView text;
    private final long startTime = 1000;
    private final long interval = 1;
    private Handler handler;
    private Runnable r;
    private MediaPlayer mp;
    private TimerTask task;
    private Timer timer;
    private long delay;
    private Boolean play = true;

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

        setContentView(R.layout.main);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(this);

        text = (TextView) this.findViewById(R.id.timer);
        mp = MediaPlayer.create(this, R.raw.cpush);
        //mp.start();
        delay = 1000;

        timer = new Timer();
        timerThread = new TimerThread();
        timer.scheduleAtFixedRate(task, 0, 10);
    }

    public long nextLong(Random rng, long n) {
        long bits, val;
        do {
            bits = (rng.nextLong() << 1) >>> 1;
            val = bits % n;
        } while (bits - val + (n - 1) < 0L);
        return val;
    }

    @Override
    public void onClick(View v) {
        button.setBackgroundResource(R.drawable.finish);
        if( play ){
            play = false;
            task.cancel();
        }
        else{
            play = true;
            /* RESTART TimerTask Hear*/
        }
    }
    public class TimerThread extends TimerTask {
        @Override
        public void run() {
            Random rand = new Random();
            final long value = nextLong(rand, 9999999999999999L);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    text.setText("" + value);
                }
            });
        }
    }
}
4

1 回答 1

1

定时器被取消后无法再次运行,您必须创建一个新对象并启动新对象

于 2014-09-22T19:46:53.590 回答