마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

Notification 확인, 취소 버튼 구현하는 방법을 모르겠습니다.

0 추천

알림을 띄우는 것 까지는 문제가 없는데 알림에 확인, 취소버튼을 기능을 구현하려면 어떻게 코딩해야되는지 모르겠습니다.

 

addAction()으로 버튼을 추가해서

알림이나 확인버튼을 누르면 MainActivity가 뜨며 알림이 사라지게하고 (상단바에서)

취소버튼을 누르면 알림이 사라지게 하고싶습니다.

 

setAutoCancel을 true로 하면 알림을 눌렀을 때 알림이 사라지는 것으로 알고있는데 사라지지 않는 것이 첫번째 문제이고

취소버튼은 구현 방법을 모르겠는게 두번째 문제입니다.

 

public class NotificationService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // Foreground 에서 실행되면 Notification 을 보여줘야 됨
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Oreo(26) 버전 이후 버전부터는 channel 이 필요함
            String channelId =  createNotificationChannel();
            Intent testIntent = new Intent(getApplicationContext(), MainActivity.class);
            PendingIntent pendingIntent
                    = PendingIntent.getActivity(this, 0, testIntent, PendingIntent.FLAG_CANCEL_CURRENT);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
            Notification notification = builder.setOngoing(true)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("일정")
                    .setContentText("일정 내용")
                    .setContentIntent(pendingIntent)
                    .setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE)
                    .setAutoCancel(true)
                    .addAction(R.drawable.ic_button_add, "확인", pendingIntent)
                    .build();

            startForeground(1, notification);
        }

        return START_STICKY;
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel() {
        String channelId = "Alarm";
        String channelName = getString(R.string.app_name);
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE);
        //channel.setDescription(channelName);
        channel.setSound(null, null);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.createNotificationChannel(channel);

        return channelId;
    }
}

액티비티와 리시버도 구현했는데 버튼 구현에는 필요없는 코드 같아서 첨부하지 않았습니다.

 

위처럼 나오는데 알림이나 확인버튼을 눌러도 알림이 사라지지 않습니다.

 

android 10버전으로 구현했습니다.

답변 부탁드립니다 ㅠㅠ

종이학 (220 포인트) 님이 2021년 11월 24일 질문
아직도 시도해보고 있는데 setOngoing을 없애도 똑같이 안되네요 ㅠ

1개의 답변

0 추천

첫번째 문제는 해결했는데 혹시 필요하신 분 있으실까봐 답변남깁니다.


일단 setAutoCancel이 작동하지 않았던 것은 알림을 띄운 것이 foreground로 계속 작동해서 그랬던 것 같습니다. 

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // Foreground 에서 실행되면 Notification 을 보여줘야 됨
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Oreo(26) 버전 이후 버전부터는 channel 이 필요함
            String channelId =  createNotificationChannel();
            Intent testIntent = new Intent(getApplicationContext(), MainActivity.class);
            PendingIntent pendingIntent
                    = PendingIntent.getActivity(this, 0, testIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            PendingIntent pendingIntent2
                    = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);

            Notification notification = builder.setOngoing(true)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build();

            builder.setSmallIcon(R.mipmap.ic_launcher)
                    .setWhen(System.currentTimeMillis())
                    .setContentTitle("일정")
                    .setContentText("일정 내용")
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE)
                    .addAction(R.drawable.ic_button_add, "확인", pendingIntent)
                    .addAction(R.drawable.ic_button_add, "취소", pendingIntent2);

            NotificationManager mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

            mgr.notify(0, builder.build());

            startForeground(1, notification);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            stopForeground(true);
        }

        stopSelf();

        return START_STICKY;
    }

위처럼 notification이랑 띄울 알림을 따로 구분해두고 startForeground에는 notification을 넣은 후 바로 stopForeground를 사용해서 없애고

띄울 알림은 NotificationManager.notify로 띄워줬더니 해결됐습니다.

 

확인버튼은 메인액티비티에

public static void CancelNotification(Context ctx, int notifyId) {
        String  s = Context.NOTIFICATION_SERVICE;
        NotificationManager mNM = (NotificationManager) ctx.getSystemService(s);
        mNM.cancel(notifyId);
    }

위 코드를 추가하고

CancelNotification(this, 0);

onCreate에 위 코드를 입력했습니다.

알림 등록할 때 등록한 notifyId를 입력해서 메인액티비티가 등장하면 해당 알림을 종료시켰습니다.

 

취소버튼도 위 방법대로 하면 될 것 같은데 아직 방법을 찾고있습니다.

이것보다 좋은 방법이나 취소버튼 구현방법을 알고계시면 답변 부탁드립니다.

종이학 (220 포인트) 님이 2021년 11월 26일 답변
...