안드로이드 - notification

YAMAMAMO·2021년 12월 20일
0

안드로이드

목록 보기
8/13

노티피케이션 예제입니다.

노티피케이션은 알림입니다. 예를 들어 카카오톡 메시지를 받았을 때 핸드폰의 상단에 카카오톡 메시지가 왔다는 알림이 나타납니다. 꺼진 화면이 켜지기도 하고, 알림 소리가 나기도 합니다. 이러한 것들을 notification을 생성해서 보여집니다. 노티피케이션을 구현해보겠습니다.

*중요 Oreo 버전 부터는 NotificationChannel 을 생성해야 알림을 받을 수 있습니다.

activity_main.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_noti"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="헤드업알림"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

string.xml

-res → value → string.xml

<resources>
    <string name="app_name">NotificationSample2</string>
    <string name="notification_channel_id">채널아이디</string>
    <string name="notification_channel_name">채널이름</string>
    <string name="notification_channel_description">테스트알림이다.</string>
</resources>

MainActivity

public class MainActivity extends AppCompatActivity {
    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);
        createNotificationChannel ();
        btn=findViewById (R.id.btn_noti);
        btn.setOnClickListener (view -> {
            createNotification ();
        });
    }
    //노티피케이션 채널 생성. 오레오버전 이후 부터 노티피케이션채널 생성 필수
    private void createNotificationChannel(){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            String channelId = getString (R.string.notification_channel_id);
            String channelName = getString (R.string.notification_channel_name);
            String channelDes = getString (R.string.notification_channel_description);
            NotificationManager notificationManager = (NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE);
            NotificationChannel notificationChannel =
                    new NotificationChannel (channelId //채널 ID
                            , channelName //채널 Name
                            , NotificationManager.IMPORTANCE_HIGH);//중요도 HIGH 부터 헤드업 알림
            notificationChannel.setDescription (channelDes);//채널설명
            notificationManager.createNotificationChannel (notificationChannel);
        }
    }
    //노티피케이션 생성
    private void createNotification(){
				String channelId = getString (R.string.notification_channel_id);
        NotificationCompat.Builder notification =
                new NotificationCompat.Builder (this, channelId)
                        .setSmallIcon (R.mipmap.ic_launcher)  //아이콘
                        .setContentTitle ("노티피케이션 테스트") //노티피케이션 타이틀
                        .setContentText ("노티피케이션 테스트 중입니다.") //본문 텍스트
                        .setAutoCancel (true); //사용자가 탭하면 자동으로 알림을 삭제

        NotificationManager notificationManager = (NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE);
        notificationManager.notify (0, notification.build ());
    }
}

노티피케이션을 생성할 때 알림소리, 진동, 앱실행등 여러가지 설정을 해 줄 수 있습니다. 추후 다양한 설정들을 추가해 보겠습니다.

profile
안드로이드 개발자

0개의 댓글