AlarmManager 관련 내용 공부하면서 짜본 예제 프로그램 입니다.
alarm발생시 작업을 수행할 broadcast를 성정한뒤 AlarmManager을 등록 합니다.
프로그램 조건
① 지정된 시간마다 알람음을 울린다.
② 슬립모드에서도 동작되어야 한다.
클래스 구성
AlarmManagerStep1.java
- main Activity
- 알람 설정/해지 버튼 이벤트 처리
AlarmReceiver.java
- extends BroadcastReceiver
- 방송수신시 알람음 발생
MySoundPlay.java
- 사운드 관련 클래스
- ../res/raw 폴더 생성후 재생할 음악 파일을 넣는다.
Output.java
- 토스트 출력 및 로그 관리 클래스
프로그램 동작
- 알람등록 버튼 클릭시 AlarmManager 등록
- 알람해지 버튼 클릭시 AlarmManager 해지
- 등록된 알람은 설정된 주기마다 알람음 발생 되며 슬립모드에서도 동작 한다.
알람음 주기를 짧게(1~5초)하고 동작하다가 슬립모드에 들어갔따 다시 나와서 잠시뒤에
Java.lang.NullPointerException 발생 하더라구요
그래서 전 브로드케스트 리시버쪽을 아래처럼 수정하니 별탈없이 동작합니다.
public class AlarmReceiver extends BroadcastReceiver {
private static final String TAG_LOG = "AlarmReceiver";
private static MySoundPlay mplay = null;
@Override
public void onReceive(Context context, Intent intent) {
try {
if(mplay == null) {
mplay = new MySoundPlay(context, R.raw.dingdong);
}
mplay.play();
}catch( Exception e ) {
Output.e(TAG_LOG, e.toString());
}
}
}
아래 코드는 문제가 발생했던 코드들인데 static 때문인지 이유를 정확히 모르겠네요 혹시 아시는분 있으시면
답변 부탁드립니다. ^^
/*
* Java.lang.NullPointerException 발생
@Override
public void onReceive(Context context, Intent intent) {
try{
MySoundPlay mplay= new MySoundPlay(context, R.raw.dingdong);
mplay.play();
}catch( Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
}
*/
/*
private static MySoundPlay mplay = null;
@Override
public void onReceive(Context context, Intent intent) {
try {
mplay = new MySoundPlay(context, R.raw.dingdong);
mplay.play();
}catch( Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
}
*/
/*
private MySoundPlay mplay = null;
@Override
public void onReceive(Context context, Intent intent) {
try {
if(mplay == null) {
mplay = new MySoundPlay(context, R.raw.dingdong);
}
mplay.play();
}catch( Exception e ) {
Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
}
*/
오오 좋은 정보 감사합니다.