<안드로이드> 일정관리프로그램 : 알림기능
원래 넣어야하는 기능이었지만 안드로이드 스튜디오 렉이 너무심해 빨리 마무리 하였다
ㅠㅠ
알수없는 렉으로 더이상 코드 작성이 어려웠다. ㅜ 원인을 찾아 해결하든가 다시깔아 봐야겟다 ..
그래서 알림 기능을 구현하기 위해 필요한 내용들을 정리 해보기로 하였다.
- 정해진시간에 Broadcast가 발생하도록 Alarm클래스작성
public class Alarm {
public void registerAlarm(Context context){
Intent intent = new Intent(context, AlarmReceiver.class );
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
calen = Calendar.getInstance();
calen.set(calen.get(Calendar.YEAR), calen.get(Calendar.MONTH), calen.get(Calendar.DAY_OF_MONTH)+1, 0,0,0);
am.set(am.RTC_WAKEUP, calen.getTimeInMillis(), pi);
}
}
AlarmReceiver에대한 intent를 생성.
BroadcastReceiver를 작동하기위한 PendingIntent를 생성한다.
Calender객체에 시간을 설정한 다음 AlarmManager의 set메소드를 이용하여
지정한시간에 PendingIntet가 수행되도록 알람을 설정한다.
즉, AlarmManager에서 지정한시간에 broadcast하면 Pendingintent를 호출시켜 intent(AlarmReceiver)를 불러올것이다.
- 정해진시간에 Broadcast가 발생하도록 Alarm클래스작성
public class Alarm {
public void registerAlarm(Context context){
Intent intent = new Intent(context, AlarmReceiver.class );
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
calen = Calendar.getInstance();
calen.set(calen.get(Calendar.YEAR), calen.get(Calendar.MONTH), calen.get(Calendar.DAY_OF_MONTH)+1, 0,0,0);
am.set(am.RTC_WAKEUP, calen.getTimeInMillis(), pi);
}
}
AlarmReceiver에대한 intent를 생성.
BroadcastReceiver를 작동하기위한 PendingIntent를 생성한다.
Calender객체에 시간을 설정한 다음 AlarmManager의 set메소드를 이용하여
지정한시간에 PendingIntet가 수행되도록 알람을 설정한다.
즉, AlarmManager에서 지정한시간에 broadcast하면 Pendingintent를 호출시켜 intent(AlarmReceiver)를 불러올것이다.
- 알림 기능을 구현하기위해서는 broadcastReceiver를 사용해야한다.
설정한 알림시간이되면 시스템(AlarmManager)에서는 브로드캐스트를 intent 형태로 해당 앱에게 전달한다.
받은 브로드캐스트 처리하기 위해 리시버를 구현하여야 한다.
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager noti = (NotificationManager)context.getSystemService(Cotext.NOTFICATION_SERVICE);
PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Buider builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(아이콘);
builder.setContentTitle("제목");
builder.setContentText("내용");
builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
builder.setAutoCancel(true);
builder.setContentIntent(pi);
noti.notify(0,builder.build());
}
}
BroadcastReceiver를 상속받아 onReceive에 브로드캐스트를 받았을때 실행할 코드를 작성한다.
PendingIntent의 getActivity메소드를 사용하여 인텐트를 생성.
NotificationCompat.Buider 클래스를 사용하여 알림을 생성, 아이콘, 제목, 내용들을 적용한다.
시스템에서 불러온 NotificationManager의 notify로 builder를 Build 한다.
즉, builder로 알림을생성, PendingIntent는 알림 클릭 시 MainActivity를 실행하기위해 setContentIntent메소드 인자로 넣어주고
시스템에서불러온 NotificationManager의 notify메소드로 Notification을 적용시킨다.
댓글
댓글 쓰기