android中簡單定時器

來源:互聯網
上載者:User

  首先說,Android系統的SDK包裡沒有Timer(J2SE裡的),所以實現定時器的功能還是會採取其他的方式。一想到非同步處理,自然就想到了android.os.Handler來代替Timer。但是想到Timer有重複執行特定的動作,這個該怎麼實現的呢?這個問題實際上你在post一個message裡時候,這個message嵌套一個自己的message就可以了。具體的代碼如下:

public class MainActivity extends Activity {
private Handler mHandler = new Handler();

private TextView mTimeLabel;
private long mStartTime = 0L;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTimeLabel = (TextView)findViewById(R.id.time);

findViewById(R.id.start).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mStartTime == 0L) {
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
}
});

findViewById(R.id.stop).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
});
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
final long start = mStartTime;
long millis = System.currentTimeMillis() - start;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;

if (seconds < 10) {
mTimeLabel.setText("" + minutes + ":0" + seconds);
} else {
mTimeLabel.setText("" + minutes + ":" + seconds);
}
//mHandler.postAtTime(this,start + (((minutes * 60) + seconds + 1) * 1000));
mHandler.postDelayed(this, 100);
}
};
}

  注意:嵌套post的時候(通常是嵌套自己),如果操作不當,會造成記憶體泄露。就像我昨天看見一篇部落格就是講到handler這個嵌套postDelay方法而造成記憶體泄露。解決這個途徑就是要注意程式退出的時候一定要執行下面的代碼:

mHandler.removeCallbacks(mUpdateTimeTask);

  內容非常簡單,說多了也是廢話。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.