在網上看了很多類似的文章,比較亂,自己總結了一下,在開發中,常見的執行定時任務的方法有以下幾種,
很簡單的描述,有什么不懂可以留言,下面來介紹一下這幾種常見的方法:
1.直接在線程中睡覺的方法,這個比較常見,操作也方便
class MThread implements Runnable { @Override public void run() { // TODO Auto-generated method stub try { do { Thread.sleep(1000); count -= 1; if (count == 0) { // time=Calendar.getInstance().getTimeInMillis()/1000+myDb.getDiffTime(); count = 30; } pb.setProgress(count); Message msg = new Message(); msg.what = 1111; mHandler.sendMessage(msg); } while (!Thread.interrupted()); } catch (Exception e) { e.printStackTrace(); } } }
2.直接使用SystemClock.sleep(1000);進行睡眠,需要注意的是這個會阻塞主線程
SystemClock.sleep(1000);
3.直接使用TimerTask進行定時
這個方法也經常使用,比如開啟的splash頁面中,常用timertask進行時間以及動畫的過渡。
Timer timer = new Timer(); TimerTask MyTask = new TimerTask() { @Override public void run() { } }; timer.schedule(MyTask, 1000);
4.常用的隨機碼生成,舉個6位數生成的例子吧,這個是生成6位隨機數
int numcode = (int) ((Math.random() * 9 + 1) * 100000); String smstext = "你本次生成的6位安全驗證碼為:" + numcode;
