android 定時器的實現

來源:互聯網
上載者:User

標籤:android   blog   http   color   io   ar   使用   java   sp   

在Android上常用的定時器有兩種,一種是Java.util.Timer,一種就是系統的AlarmService了。 


實驗1:使用Java.util.Timer。 
在onStart()創建立Timer,每5秒更新一次計數器,並啟動。 
  
  mTimer = new Timer();       
  mTimer.schedule(new TimerTask() {           
              @Override
              public void run() {
                  ++mCount;
                  mHandler.sendEmptyMessage(0);               
              }
          }, 5*1000, 5*1000);
  
當串連USB線進行調試時,會發現一切工作正常,每5秒更新一次介面,即使是按下電源鍵,仍然會5秒觸發一次。 
當拔掉USB線,按下電源鍵關閉螢幕後,過一段時間再開啟,發現定時器明顯沒有繼續計數,停留在了關閉電源鍵時的數字。 

實驗2:使用AlarmService: 
2.1通過AlarmService每個5秒發送一個廣播,setRepeating時的類型為AlarmManager.ELAPSED_REALTIME。 
  
  AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);  
  am.setRepeating(AlarmManager.ELAPSED_REALTIME, firstTime, 5*1000, sender);

拔掉USB線,按下電源鍵,過一段時間再次開啟螢幕,發現定時器沒有繼續計數。 
2.2setRepeating是的類型設定為AlarmManager.ELAPSED_REALTIME_WAKEUP 
  
  AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);   
  am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 5*1000, sender);

拔掉USB線,按下電源鍵,過一點時間再次開啟螢幕,發現定時器一直在計數。 

如此看來,使用WAKEUP才能保證自己想要的定時器一直工作,但是肯定會引起耗電量的增加   

AlarmManager的使用機制有的稱呼為全域定時器,有的稱呼為鬧鐘。通過對它的使用,個人覺得叫全域定時器比較合適,其實它的作用和Timer有點相似。都有兩種相似的用法:(1)在指定時間長度後執行某項操作(2)周期性的執行某項操作

AlarmManager對象配合Intent使用,可以定時的開啟一個Activity,發送一個BroadCast,或者開啟一個Service.

下面的代碼詳細的介紹了兩種定時方式的使用:

 (1)在指定時間長度後執行某項操作

 

Java代碼  
  1.      //操作:發送一個廣播,廣播接收後Toast提示定時操作完成  
  2. <!--  
  3.   
  4. Code highlighting produced by Actipro CodeHighlighter (freeware)  
  5. http://www.CodeHighlighter.com/  
  6.   
  7. -->     Intent intent =new Intent(Main.this, alarmreceiver.class);  
  8.     intent.setAction("short");  
  9.     PendingIntent sender=  
  10.         PendingIntent.getBroadcast(Main.this, 0, intent, 0);  
  11.       
  12.     //設定一個五秒後的時間  
  13.     Calendar calendar=Calendar.getInstance();  
  14.     calendar.setTimeInMillis(System.currentTimeMillis());  
  15.     calendar.add(Calendar.SECOND, 5);  
  16.       
  17.     AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);  
  18.     alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);  
  19.     //或者以下面方式簡化  
  20.     //alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5*1000, sender);  
  21.       
  22.     Toast.makeText(Main.this, "五秒後alarm開啟", Toast.LENGTH_LONG).show();  
 

//注意:receiver記得在manifest.xml註冊

 Java代碼  
  1. <!--  
  2.   
  3. Code highlighting produced by Actipro CodeHighlighter (freeware)  
  4. http://www.CodeHighlighter.com/  
  5.   
  6. -->    public static class alarmreceiver extends BroadcastReceiver{  
  7.   
  8.         @Override  
  9.         public void onReceive(Context context, Intent intent) {  
  10.             // TODO Auto-generated method stub  
  11.             if(intent.getAction().equals("short")){  
  12.                 Toast.makeText(context, "short alarm", Toast.LENGTH_LONG).show();  
  13.             }else{  
  14.                 Toast.makeText(context, "repeating alarm",   
  15.                       Toast.LENGTH_LONG).show();  
  16.             }  
  17.         }  
  18.     }  
 

(2)周期性的執行某項操作

 

Java代碼  
  1. <!--  
  2.   
  3. Code highlighting produced by Actipro CodeHighlighter (freeware)  
  4. http://www.CodeHighlighter.com/  
  5.   
  6. -->    Intent intent =new Intent(Main.this, alarmreceiver.class);  
  7.     intent.setAction("repeating");  
  8.     PendingIntent sender=PendingIntent  
  9.         .getBroadcast(Main.this, 0, intent, 0);  
  10.       
  11.   
  12.     //開始時間  
  13.     long firstime=SystemClock.elapsedRealtime();  
  14.   
  15.     AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);  
  16.   
  17.   //5秒一個周期,不停的發送廣播  
  18.     am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP  
  19.             , firstime, 5*1000, sender);  
 

 AlarmManager的setRepeating()相當於Timer的Schedule(task,delay,peroid);有點差異的地方時Timer這個方法是指定延遲多長時間

以後開始周期性的執行task;

AlarmManager的取消:(其中需要注意的是取消的Intent必須與啟動Intent保持絕對一致才能支援取消AlarmManager)

 

 

Java代碼  
  1. <!--  
  2.   
  3. Code highlighting produced by Actipro CodeHighlighter (freeware)  
  4. http://www.CodeHighlighter.com/  
  5.   
  6. -->  Intent intent =new Intent(Main.this, alarmreceiver.class);  
  7.   intent.setAction("repeating");  
  8.   PendingIntent sender=PendingIntent  
  9.          .getBroadcast(Main.this, 0, intent, 0);  
  10.   AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);  
  11.   alarm.cancel(sender);  

android 定時器的實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.