본문 바로가기
안드로이드 자바

[JAVA][Android] 알림(Notification) 그룹 클릭 이벤트 감지하기

by teamnova 2024. 8. 23.
728x90

오늘은 알림(Notification) 클릭 시, 하나의 알림을 클릭했을 때와 알림 그룹을 클릭했을 때의 이벤트를 감지하여 각각 다른 액티비티를 실행해보도록 하겠습니다. 

 

아래 예제는 알림 그룹을 클릭한 경우, NotificationGroupActivity가 실행되며 클릭한 그룹key를 화면에 출력하고, 

하나의 알림을 클릭한 경우, NotificationItemActivity 가 실행되며 클릭한 알림의 내용을 화면에 출력합니다. 

 

레이아웃 xml 파일 코드 (main.xml )

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="그룹1 - 첫번재 알림"
        android:textSize="20dp"/>

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="그룹1 - 두번재 알림"
        android:textSize="20dp"/>
    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="그룹2 - 첫번재 알림"
        android:textSize="20dp"/>
    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="그룹2 - 두번재 알림"
        android:textSize="20dp"/>
</LinearLayout>

 

레이아웃 xml 파일 코드 (noti_group.xml )

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="알림 그룹 액티비티"
        android:textSize="30dp"
        android:textColor="@color/black"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"/>


    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="받은 알림 텍스트"
        android:textSize="30dp"
        android:textColor="@color/black"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

 

 

레이아웃 xml 파일 코드 (noti_item.xml )

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="알림 아이템 액티비티"
        android:textSize="30dp"
        android:textColor="@color/black"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"/>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="받은 알림 텍스트"
        android:textSize="30dp"
        android:textColor="@color/black"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

 

 

MainActivity 자바 코드

public class MainActivity extends AppCompatActivity {
    private static final String CHANNEL_ID = "테스트 알림";
    private static final String GROUP_1 = "GROUP_1";
    private static final String GROUP_2 = "GROUP_2";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        createNotificationChannels();

        Button button1 = findViewById(R.id.button);
        Button button2 = findViewById(R.id.button2);
        Button button3 = findViewById(R.id.button3);
        Button button4 = findViewById(R.id.button4);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNotification("그룹 1 - 알림 1", "1번 그룹의 첫번째 알림입니다. ", CHANNEL_ID, GROUP_1);
                showGroupSummary(CHANNEL_ID, GROUP_1);
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNotification("그룹 1 - 알림 2", "1번 그룹의 두번째 알림입니다. ", CHANNEL_ID, GROUP_1);
                showGroupSummary(CHANNEL_ID, GROUP_1);
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNotification("그룹 2 - 알림 1", "2번 그룹의 첫번째 알림입니다. ", CHANNEL_ID, GROUP_2);
                showGroupSummary(CHANNEL_ID, GROUP_2);
            }
        });

        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNotification("그룹 2 - 알림 2", "2번 그룹의 두번째 알림입니다. ", CHANNEL_ID, GROUP_2);
                showGroupSummary(CHANNEL_ID, GROUP_2);
            }
        });
    }

    private void createNotificationChannels() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "알림 채널",
                    NotificationManager.IMPORTANCE_HIGH
            );
            channel.setDescription("알림 채널 입니다");

            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(channel);
            }
        }
    }

    private void showNotification(String title, String content, String channelId, String groupKey) {
        Intent intent = new Intent(this, NotificationCheckActivity.class);
        intent.putExtra("isGroup", false);
        intent.putExtra("content", content);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);


        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
                .setSmallIcon(R.drawable.ic_sms)
                .setContentTitle(title)
                .setContentText(content)
                .setGroup(groupKey)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.notify((int) System.currentTimeMillis(), builder.build());
        }
    }

    private void showGroupSummary(String channelId, String groupKey) {
        Intent intent = new Intent(this, NotificationCheckActivity.class);
        intent.putExtra("isGroup", true);
        intent.putExtra("content", groupKey);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent gruopPendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis()/* Request code */, intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        NotificationCompat.Builder summaryBuilder = new NotificationCompat.Builder(this, channelId)
                .setSmallIcon(R.drawable.ic_sms)
                .setGroup(groupKey)
                .setGroupSummary(true)
                .setContentIntent(gruopPendingIntent)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.notify(groupKey.hashCode(), summaryBuilder.build());
        }
    }
}

 

 

NotificationCheckActivity 자바 코드

public class NotificationCheckActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        boolean isGroup = intent.getBooleanExtra("isGroup", false);
        String  noti_content = intent.getStringExtra("content");
        Log.i("check",isGroup+"");
        Log.i("check",noti_content+"");

        if (isGroup) {
            Intent groupIntent = new Intent(this, NotificationGroupActivity.class);
            groupIntent.putExtra("content", noti_content);
            startActivity(groupIntent);
        } else {
            Intent chatIntent = new Intent(this, NotificationItemActivity.class);
            chatIntent.putExtra("content", noti_content);
            startActivity(chatIntent);
        }

        finish();
    }
}

 

 

NotificationGroupActivity 자바 코드

public class NotificationGroupActivity  extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.noti_group);
        TextView t = findViewById(R.id.textView);
        TextView t2 = findViewById(R.id.textView2);

        Intent intent = getIntent();
        String  noti_content = intent.getStringExtra("content");
        t2.setText(noti_content);
    }
}

 

 

NotificationItemActivity 자바 코드

public class NotificationItemActivity   extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.noti_item);
        TextView t = findViewById(R.id.textView);
        TextView t2 = findViewById(R.id.textView2);

        Intent intent = getIntent();
        String  noti_content = intent.getStringExtra("content");
        t2.setText(noti_content);
    }
}