Android API level 16을 기준으로 합니다. (4.1.x)
우선 알람 매니저를 가져오는 방법
AlarmManager alarmManager = (AlarmManager)this.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
알람 매니저에 알람을 설정하는 방법
long alarmTime = System.currentTimeMillis() + 5 * 1000; // 지금부터 5초 뒤 alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, createPendingIntent("kr.pe.bspfp.alarm", 123, "test"));
알람 매니저에서 알람을 해제하는 방법
alarmManager.set(createPendingIntent("kr.pe.bspfp.alarm", 123, null));
PendingIntent 생성
private PendingIntent createPendingIntent(String action, int requestCode, String msg) { Intent intent = new Intent(action); if (msg != null) { Bundle bundle = new Bundle(); bundle.putInt("RequestCode", requestCode); bundle.putString("Message", msg); intent.putExtra("Params", bundle); } return PendingIntent.getBroadcast(this.getApplicationContext(), requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT); }
set에서 사용하는 타입 설명
- AlarmManager.ELAPSED_REALTIME
부팅 후 지난 시간이 설정된 시간과 같아지면 알림 - AlarmManager.ELAPSED_REALTIME_WAKEUP
AlarmManager.ELAPSED_REALTIME와 동일, 알림시 장치를 깨우는 것이 차이점 - AlarmManager.RTC
UTC 기분 밀리초 시간, System.currentTimeMillis() 하면 나오는 그 시간 - AlarmManager.RTC_WAKEUP
AlarmManager.RTC와 동일, 알림시 장치를 깨우는 것이 차이점
AlarmManager.cancel()에 대해
PendingIntent에 설정된 Inten의 filterEquals()가 true 인 대상을 취소
위 예제에서는 같은 action과 request code를 가지면 취소되었음
PendingIntent.FLAG_…
- PendingIntent.FLAG_CANCEL_CURRENT
중복된 PendingIntent가 존재하면 취소하고 새로 생성 - PendingIntent.FLAG_NO_CREATE
중복된 PendingIntent가 존재하면 생성하지 않고 null 반환 - PendingIntent.FLAG_ONE_SHOT
일회용 PendingIntent - PendingIntent.FLAG_UPDATE_CURRENT
중복된 PendingIntent가 존재하면 생성하지 않고 extra 데이터만 변경