AlarmManager

AlarmManager鬧鐘的設置
可以作爲一個特定的時間去觸發一個事件
三件事;
1、建立一接收者
receiver,在onreceiver裏面寫觸發
/**
 * 鬧鈴接受者,時間到了會觸發notification的服務
 * @author Administrator
 *
 */
public class AlarmReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent arg1) {
      //開啓消息推送的功能
      Intent service = new Intent(context, MessageNotifactionService.class);
      context.startService(service);
 }
}


2、在manifest裏面註冊接受者
<!-- 鬧鈴定時的接受者 -->
        <receiver android:name="com.wc.xph.receiver.AlarmReceiver">
            </receiver>

3、在程序開啓的時候就執行鬧鈴設置
/**
  * 鬧鈴的方法,設置18.30分的推送
  */
 private void startAlarm(){
  Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);  
  PendingIntent sender = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);  

  long firstTime = SystemClock.elapsedRealtime(); // 開機之後到現在的運行時間(包括睡眠時間)  
  long systemTime = System.currentTimeMillis();  

  Calendar calendar = Calendar.getInstance();  
  calendar.setTimeInMillis(System.currentTimeMillis());  
  // 這裏時區需要設置一下,不然會有8個小時的時間差  
  calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));  
  calendar.set(Calendar.HOUR_OF_DAY, 18);    
  calendar.set(Calendar.MINUTE, 0);
  calendar.set(Calendar.SECOND, 0);  
  calendar.set(Calendar.MILLISECOND, 0);  
  // 選擇的定時時間  
  long selectTime = calendar.getTimeInMillis();  
  // 如果當前時間大於設置的時間,那麼就從第二天的設定時間開始  
  if(systemTime > selectTime) {    
   calendar.add(Calendar.DAY_OF_MONTH, 1);
   selectTime = calendar.getTimeInMillis();  
  }
  // 計算現在時間到設定時間的時間差  
  long time = selectTime - systemTime;  
  firstTime = firstTime + time;
  // 進行鬧鈴註冊  
  AlarmManager manager = (AlarmManager)getSystemService(ALARM_SERVICE);  
  manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,  
    firstTime, DAY, sender);  
 }
//24小時
 public static final long DAY = 1000L * 60 * 60 * 24;



在設置了定時達額時候還要在不需要的時候需要取消這個定時的綁定任務,取消這個鬧鈴定時的任務是通過以下的方式來進行取消的
Intent intent = new Intent("cn.pocketdigi.update.alarm"); 
intent.setClass(this, AlarmReceiver.class); 
PendingIntent pi=PendingIntent.getBroadcast(this, 0, intent,0); 
AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE); 
alarm.cancel(pi); 
發佈了38 篇原創文章 · 獲贊 25 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章