2013年5月17日 星期五

[Android] 鬧鐘(AlarmMamager and PendingIntent) 下篇

上篇鬧鐘的片段
Intent intent = new Intent(MainActivity.this,
      PlayReceiver.class);
    intent.putExtra("msg", "play_voice");
    intent.addCategory(String.valueOf(SystemClock.elapsedRealtime()));

    long elapsed = SystemClock.elapsedRealtime() + 60 * 1000; // millis

    PendingIntent pi = PendingIntent.getBroadcast(
      MainActivity.this, 1, intent,
      PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, elapsed, pi);

當我們設定鬧鐘後,如果想取消的話呢?
很簡單,只要呼叫cancel function即可
am.cancel(pi);

那如何確認鬧鐘是否真的被取消呢?
主要是利用PendingIntent.FLAG_NO_CREATE這個參數,
當被包起來的Inent不存在,得回傳null
 
  boolean alarmUp = (PendingIntent.getBroadcast(MainActivity.this, 1,
    intent, PendingIntent.FLAG_NO_CREATE) != null);

  if (alarmUp) 
      Log.d("myTag", "Alarm is already active");
  else
      Log.d("myTag", "Alarm is not already active");

沒有留言:

張貼留言