Android计时器Timer的使用方法

时间:2022-08-31 20:33:13

Android 可以通过Timer定时器来完成定时更新ui的操作,代码如下

package com.example.timertext;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {


private Timer mTimer;
private TimerTask mTimerTask;
private Handler handler;
private Button btn;
private TextView tv;
private int j=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView) findViewById(R.id.tv);
btn=(Button) findViewById(R.id.btn);

handler=new Handler(){
@Override
public void handleMessage(Message msg) {

switch (msg.arg1) {
case 1:
tv.setText(""+j);
Log.e("name", ""+j);
j++;
if(j>10){
mTimerTask.cancel();
mTimer.cancel();
}
break;
}
}
};



btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
mTimer=new Timer();
mTimerTask=new TimerTask() {

@Override
public void run() {

Message msg=Message.obtain();
msg.arg1=1;
handler.sendMessage(msg);

}
};

mTimer.schedule(mTimerTask, 1000, 1000);
}
});




}

}