Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

ParkPro's App development store

[Android] 안드로이드 앱 푸쉬 알림 기능 코드 (App Notification example code) 본문

Android

[Android] 안드로이드 앱 푸쉬 알림 기능 코드 (App Notification example code)

박프로ParkPro 2020. 5. 17. 22:42

 

안녕하세요. 박프로입니다.

폰을 사용하다보면 각종 앱들의 광고, 찜해놓은 웹툰의 업로드 알람, 구글 캘린더의 스케줄 알람 등이 진동과 함께 폰 상단에 뜨는 경우들이 있습니다. 이번 글에서는 이와 같은 안드로이드 폰에서의 앱 알람 기능에 대해 알아보겠습니다.

 

구현 내용

이번에 설명드릴 예제 코드를 구현하면 아래 그림처럼 나타납니다.

Title과 Message를 입력하게 되어있고, 알림 채널을 설정하게 되어있습니다.

안드로이드에서는 폰에 알림 기능을 실행할 때 항상 채널을 입력해야 합니다.

 

 

 

 

타이틀에 Greeting, 메시지에 Hello를 입력해서 채널 1번 전송 버튼을 누르면

아래 그림처럼 폰에 알람이 뜨게 됩니다.

알림이 뜰 때 알람 타입(소리 or 진동), 이모티콘 ([1]모양) 등 설정도 가능합니다.

 

 

 

 

코드 리뷰

NotificationHelper class에서 알림 메소드를 만들고

layout에서는 Text와 Title 입력값, 알림 센드 버튼을 만들어

MainActivity에서 동작하는 방식입니다.

 

[1] NotificationHelper

- Channel1과 Channel2에 ID와 Name을 부여한 후 채널을 생성(NotificationManager 이용)

- 이 때 Lights/Vibration/Color 등 채널 특성 입력이 가능

- NotificationCompat.Builder를 이용해서 알림 제목/내용/아이콘 입력하는 메소드를 생성

 

public class NotificationHelper extends ContextWrapper {
    public static final String channel1ID = "channel1ID";
    public static final String channel1Name = "channel 1 ";
    public static final String channel2ID = "channel2ID";
    public static final String channel2Name = "channel 2 ";

    private NotificationManager mManager;

    public NotificationHelper(Context base) {
        super(base);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createChannels();
        }
    }

    public void createChannels(){
        NotificationChannel channel1 = new NotificationChannel(channel1ID,channel1Name, NotificationManager.IMPORTANCE_DEFAULT);
        channel1.enableLights(true);
        channel1.enableVibration(true);
        channel1.setLightColor(R.color.colorPrimary);
        channel1.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

        getManager().createNotificationChannel(channel1);

        NotificationChannel channel2 = new NotificationChannel(channel2ID,channel2Name, NotificationManager.IMPORTANCE_DEFAULT);
        channel2.enableLights(true);
        channel2.enableVibration(true);
        channel2.setLightColor(R.color.colorPrimary);
        channel2.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

        getManager().createNotificationChannel(channel2);

    }

    public NotificationManager getManager() {
        if (mManager == null){
            mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }

        return mManager;
    }

    public NotificationCompat.Builder getChannel1Notification(String title, String message){
        return new NotificationCompat.Builder(getApplicationContext(), channel1ID)
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(R.drawable.ic_one);
    }

    public NotificationCompat.Builder getChannel2Notification(String title, String message){
        return new NotificationCompat.Builder(getApplicationContext(), channel2ID)
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(R.drawable.ic_two);
    }
}

 

[2] MainActivity

 

layout의 send button을 눌렀을 때 notification을 보내도록 구성

 

public class MainActivity extends AppCompatActivity {
    private EditText editTextTitle;
    private EditText editTextMessage;
    private Button buttonChannel1;
    private Button buttonChannel2;
    private NotificationHelper mNotificationHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextTitle =   findViewById(R.id.edittext_title);
        editTextMessage = findViewById(R.id.edittext_message);
        buttonChannel1 =  findViewById(R.id.button_channel1);
        buttonChannel2 =  findViewById(R.id.button_channel2);
        mNotificationHelper = new NotificationHelper(this);

        buttonChannel1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                sendOnChannel1(editTextTitle.getText().toString(), editTextMessage.getText().toString());
            }
        });

        buttonChannel2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                sendOnChannel2(editTextTitle.getText().toString(), editTextMessage.getText().toString());
            }
        });
    }

    public void sendOnChannel1(String title, String message){
        NotificationCompat.Builder nb = mNotificationHelper.getChannel1Notification(title, message);
        mNotificationHelper.getManager().notify(1, nb.build());
    }

    public void sendOnChannel2(String title, String message){
        NotificationCompat.Builder nb = mNotificationHelper.getChannel2Notification(title, message);
        mNotificationHelper.getManager().notify(2, nb.build());
    }
}

 

[3] activity_main.xml

 

Channel1과 Channel2의 아이콘은 Vector Asset에서 가져왔습니다.

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/edittext_title"
        android:hint="Title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <EditText
        android:id="@+id/edittext_message"
        android:hint="Message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/button_channel1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="send on channel1"/>
    <Button
        android:id="@+id/button_channel2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="send on channel2"/>

</LinearLayout>

 

알람 앱을 만드는 과정 중에 있는데

반드시 필요한 기능이라서 포스팅 겸 기록을 남깁니다.

 

모두 좋은 하루 보내시길!