package cn.jinyejun.ui_progressbardemo;import java.util.Timer;import java.util.TimerTask;import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.widget.ProgressBar;public class MainActivity extends ActionBarActivity { private ProgressBar pb =null; private Timer timer = null; private TimerTask timerTask = null; private int progress = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pb = (ProgressBar) findViewById(R.id.progressBar); } @Override protected void onResume() { super.onResume(); startTimer(); } @Override protected void onStop() { super.onStop(); stopTimer(); } /** * 启动计时器 */ private void startTimer(){ if(timer == null){ timer = new Timer(); timerTask = new TimerTask() { @Override public void run() { progress+=1; pb.setProgress(progress); } }; timer.schedule(timerTask, 1000,50); } } /** * 关闭计时器并释放资源 */ private void stopTimer(){ if(timer !=null){ timerTask.cancel(); timer.cancel(); timerTask = null; timer = null; } }}
?