반응형
    
    
    
  알림(Notification)은 화면 상단에 정보를 표시하여 사용자가 알 수 있도록 한다 (카톡 메세지 받은거 알림)
백그라운드에서 동작하는 서비스에서 알림을 표시하면 사용자에게 알려줄 수 있다
알림은 NotificationManager 시스템 서비스를 이용해 화면 상단에 띄울 수 있다
알림을 띄우루면 Notification 객체를 만들어야 하는데 이 객체는 NotificationCompat.Builder 객체를 이용해서 만든다
activity_main
<?xml version="1.0" encoding="utf-8"?>
<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/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="알림 띄우기"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:text="알림 띄우고 클릭하기"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity
package com.example.a81_notification;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
    NotificationManager manager;
    private static String CHANNEL_ID = "channel1";
    private static String CHANNEL_NAME = "Channel1";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showNoti1();
            }
        });
    }
    public void showNoti1() {
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            오레오(26) 버전 이후에서는 알림 채널이 지정되어야 함
//            채널은 createNotificationChannel 메소드를 이용해 생성
            manager.createNotificationChannel(new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT));
            builder = new NotificationCompat.Builder(this, CHANNEL_ID);
        } else {
            builder = new NotificationCompat.Builder(this);
        }
        builder.setContentTitle("간단 알림");
        builder.setContentText("알림 메세지입니다.");
        builder.setSmallIcon(android.R.drawable.ic_menu_view);
        Notification noti = builder.build();
//        상단 알림 띄우기
        manager.notify(1, noti);
    }
}
여기까지만 하고 앱을 실행하면 '알림 띄우기' 버튼을 누르면 상단 알림이 뜨지만, 알림을 눌렀을 때의 동작에 관해서는 만들지 않았다
'알림 띄우고 클릭하기' 버튼을 눌렀을 때는 PendingIntent를 만들어 Notification을 만들 때 설정할 것이다
PendingIntent는 Intent와 유사하지만 시스템에서 대기하는 역할을 한다
그리고 원하는 상황이 만들어졌을 때 시스템에 의해 해석되고 처리된다
예를 들어 액티비티를 띄우는 역할을 하는 메소드가 startActivity 또는 startActivityForResult인데 이 메소드를 호출하면 시스템에서는 즉시 해석하고 처리한다
하지만 PendingIntent는 지정된 상황이 될 때까지 보관하고 있게 된다
MainActivity
package com.example.a81_notification;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
    NotificationManager manager;
    private static String CHANNEL_ID = "channel1";
    private static String CHANNEL_NAME = "Channel1";
    private static String CHANNEL_ID2 = "channel2";
    private static String CHANNEL_NAME2 = "Channel2";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showNoti1();
            }
        });
        Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showNoti2();
            }
        });
    }
    public void showNoti1() {
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            오레오(26) 버전 이후에서는 알림 채널이 지정되어야 함
//            채널은 createNotificationChannel 메소드를 이용해 생성
            manager.createNotificationChannel(new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT));
            builder = new NotificationCompat.Builder(this, CHANNEL_ID);
        } else {
            builder = new NotificationCompat.Builder(this);
        }
        builder.setContentTitle("간단 알림");
        builder.setContentText("알림 메세지입니다.");
        builder.setSmallIcon(android.R.drawable.ic_menu_view);
        Notification noti = builder.build();
//        상단 알림 띄우기
        manager.notify(1, noti);
    }
    public void showNoti2() {
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            manager.createNotificationChannel(new NotificationChannel(CHANNEL_ID2, CHANNEL_NAME2, NotificationManager.IMPORTANCE_DEFAULT));
            builder = new NotificationCompat.Builder(this, CHANNEL_ID2);
        } else {
            builder = new NotificationCompat.Builder(this);
        }
        Intent intent = new Intent(this, MainActivity.class);
//        PendingIntent 객체 만들기
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 101, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentTitle("간단 알림");
        builder.setContentText("알림 메세지입니다.");
        builder.setSmallIcon(android.R.drawable.ic_menu_view);
        
//        알림을 클릭했을 때, 자동으로 알림 표시를 삭제하라는 설정
        builder.setAutoCancel(true);
//        setContentIntent 메소드에는 PendingIntent 객체가 파라미터로 전달되었고,
//        PendingIntent 객체에는 Intent 객체가 파라미터로 전달되었다
//        그러면 알림을 클릭했을 때 이 Intent 객체를 이용해 액티비티를 띄워준다
//        액티비티가 MainActivity가 뜨도록 MainActivity.class로 설정했다
        builder.setContentIntent(pendingIntent);
        Notification noti = builder.build();
        manager.notify(2, noti);
    }
}
반응형
    
    
    
  '안드로이드' 카테고리의 다른 글
| 푸시 서비스 사용하기 - 메세지 전송 앱 만들기 (0) | 2021.11.10 | 
|---|---|
| 푸시 서비스 사용하기 (0) | 2021.11.10 | 
| 진동과 소리로 알려주기 (0) | 2021.11.10 | 
| 지도에 아이콘 추가, 오버레이 (0) | 2021.11.09 | 
| 현재 위치의 지도 보여주기 (0) | 2021.11.08 | 
 
									
								