Before 2022/Android

안드로이드 Notification 클래스로 관리하기(알림, 브로드캐스트)

Eljoe 2018. 8. 24. 12:52
NotificationUtil Class
public class NotificationUtil extends BroadcastReceiver {
    private String channelId = "channel";
    private String channelName = "channelName";

    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        
        //오레오 대응
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            int importance = NotificationManager.IMPORTANCE_HIGH;

            NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);

            notificationManager.createNotificationChannel(notificationChannel);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context.getApplicationContext(), channelId);

        Intent notificationIntent = new Intent(context.getApplicationContext(), SmartIdActivity.class);  // 알림 클릭 시 이동할 액티비티 지정

        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        // FLAG_UPDATE_CURRENT : 이미 생성된 PendingIntent가 존재하면 해당 Intent의 Extra Data만 변경한다.
        PendingIntent pendingIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentTitle("알람") //제목
                .setContentText("알람 테스트입니다") //내용
                .setDefaults(Notification.DEFAULT_ALL) //알림 설정(사운드, 진동)
                .setAutoCancel(true) //터치 시 자동으로 삭제할 지 여부
                .setPriority(NotificationCompat.PRIORITY_HIGH) // 알림의 중요도
                .setSmallIcon(R.drawable.ic_sun)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_sun))
                .setContentIntent(pendingIntent);

        notificationManager.notify(0, builder.build());
    }
}
브로드캐스트를 상속한 클래스(onReceive) 

오레오에서는 여러 알림을 효과적으로 관리하기 위해 NotificationChannel을 적용해줘야한다. (Channel 별 알림을 관리하기 위함)


AlarmUtil Class
public class AlarmUtil {
    private static final long FIVE_TO_HOUR = 1000 * 60 * 5; // 5분

    // 알람 추가 메소드
    public static void setAlarm(Context context, Calendar cal, int requestCode){
        AlarmManager fiveToHourAlarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

        Intent fiveIntent = new Intent(context, NotificationUtil.class);
       
        // FLAG_CANCEL_CURRENT : 이전에 생성한 PendingIntent 는 취소하고 새롭게 만든다
        PendingIntent fiveSender = PendingIntent.getBroadcast(context, requestCode, fiveIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        long localTime = System.currentTimeMillis();
        long targetFiveTime = cal.getTimeInMillis();
        
        // AlarmManager.INTERVAL_DAY : 24시간
        if(localTime > targetFiveTime){
            targetFiveTime += AlarmManager.INTERVAL_DAY;
        }

        if((targetFiveTime - localTime) < FIVE_TO_HOUR){
            targetFiveTime += AlarmManager.INTERVAL_DAY;
        }

        fiveToHourAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, (targetFiveTime-FIVE_TO_HOUR), AlarmManager.INTERVAL_DAY, fiveSender);

        SimpleDateFormat format = new SimpleDateFormat("MM/dd kk:mm:ss");
        String setTargetFiveTime = format.format(new Date(targetFiveTime-FIVE_TO_HOUR));

        Log.d("NotiTEST", "FiveToHour : " + setTargetFiveTime);
    }

    //알람 해제 메소드
    public static void releaseAlarm(Context context, int requestCode){
        AlarmManager fiveToHourAlarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

        Intent fiveIntent = new Intent(context, NotificationUtil.class);

        PendingIntent fiveSender = PendingIntent.getBroadcast(context, requestCode, fiveIntent, 0);

        fiveToHourAlarmManager.cancel(fiveSender);

        Log.d("NotiTEST", "AlarmUtil Canel");
    }
}