试图在Android上制作计时器

时间:2012-11-22 20:43:00

标签: java android

我正在使用计时器和sheduleAtFixedRate方法在Android上制作计时器,但看起来在计时器的run方法中调用我的textview会使我的应用程序停止。我做错了什么?这是我的代码:

Button boton_iniciar;
TextView texto_cronometro;
Timer count;
int a = 0;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cronometro);

    /**********************/
    boton_iniciar = (Button) findViewById(R.id.button1);
    texto_cronometro = (TextView) findViewById(R.id.textView1);
    count= new Timer("Contador");
    boton_iniciar.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            count.scheduleAtFixedRate(new TimerTask() {         
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    a++;
                    texto_cronometro.setText(String.valueOf(a));
                }
            }, 100, 100);
        }
    });
}

3 个答案:

答案 0 :(得分:0)

所有更改或触摸UI对象的操作都应该在Thread UI上运行。 尝试:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cronometro);

    /**********************/
    boton_iniciar = (Button) findViewById(R.id.button1);
    texto_cronometro = (TextView) findViewById(R.id.textView1);
    count= new Timer("Contador");
    boton_iniciar.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            count.scheduleAtFixedRate(new TimerTask() {         
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    a++;
                    ActivityCronometro.this.runOnUiThread(new Runnable() {          
                    @Override
                    public void run() {
                        texto_cronometro.setText(String.valueOf(a));

                    }
                });

                }
            }, 100, 100);
        }
    });
}

答案 1 :(得分:0)

您正在尝试更新ui线程外的用户界面。

texto_cronometro.setText(String.valueOf(a));替换为:

<youractivityname>.this.runOnUiThread(new Runnable() {

    public void run() {
        texto_cronometro.setText(String.valueOf(a));
    }
});

答案 2 :(得分:0)

在runnable中操作界面控制。

参考代码:

private Handler handler = new Handler( );

private Runnable runnable = new Runnable( ) {
 public void run ( )
 {
 atextview.setText(String.valueOf(a));
 handler.postDelayed(this,1000); //if continue Timer,use this sentence.
 }
 };
 handler.postDelayed(runnable,1000); // begin Timer
 handler.removeCallbacks(runnable); //stop Timer