Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android에서 싱글톤(Singleton) 패턴으로 알림(Notification) 구현하기

싱글톤 디자인 패턴이란?

본격적인 예제를 살펴보기 전에, 싱글톤(singleton) 디자인 패턴이 무엇인지 먼저 이해할 필요가 있습니다. 싱글톤은 하나의 클래스에 대해 인스턴스 생성을 단 하나로 제한하는 디자인 패턴입니다. 대표적인 활용 사례로는 동시성(concurrency) 제어와 애플리케이션이 데이터 저장소에 접근할 수 있는 중앙 집중식 접근 지점을 만드는 것이 있습니다.

이 글에서는 Android에서 싱글톤 클래스를 활용하여 알림(Notification)을 표시하는 방법을 단계별로 살펴보겠습니다.

1단계: 새 프로젝트 생성

Android Studio에서 File ⇒ New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 새 프로젝트를 만듭니다.

2단계: 레이아웃 파일 수정

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
    xmlns:tools = "https://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity"
    android:orientation = "vertical">
    <Button
        android:id = "@+id/show"
        android:text = "Show notification from singleTone"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content" />
</LinearLayout>

위 코드에서는 화면에 버튼 하나를 배치했습니다. 사용자가 이 버튼을 클릭하면 싱글톤 클래스에서 알림을 가져와 화면에 표시하게 됩니다.

3단계: MainActivity 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
    Button show;
    singleTonExample singletonexample;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        show = findViewById(R.id.show);
        singletonexample = singleTonExample.getInstance();
        singletonexample.init(getApplicationContext());
        show.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View v) {
                singletonexample.notification(MainActivity.this);
            }
        });
    }
}

위 코드에서는 싱글톤 클래스 역할을 할 singleTonExample을 사용했습니다. 이제 singleTonExample.java 파일을 새로 생성하고 아래 코드를 추가합니다.

4단계: 싱글톤 클래스 작성

package com.example.andy.myapplication;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.support.annotation.RequiresApi;
import android.widget.Toast;
public class singleTonExample {
    public static final String ANDROID_CHANNEL_ID = "com.example.andy.myapplication";
    private static singleTonExample ourInstance = new singleTonExample();
    private Context appContext;
    private singleTonExample() { }
    public static Context get() {
        return getInstance().getContext();
    }
    public static synchronized singleTonExample getInstance() {
        return ourInstance;
    }
    public void init(Context context) {
        if (appContext == null) {
            this.appContext = context;
        }
    }
    private Context getContext() {
        return appContext;
    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void notification(final MainActivity mainActivity) {
        NotificationManager notif =(NotificationManager)mainActivity.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel androidChannel = new NotificationChannel(ANDROID_CHANNEL_ID,
            "Notification Channel", NotificationManager.IMPORTANCE_DEFAULT);
        androidChannel.enableLights(true);
        androidChannel.enableVibration(true);
        androidChannel.setLightColor(Color.GREEN);
        androidChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        notif.createNotificationChannel(androidChannel);
        Notification notify = null;
        notify = new  Notification.Builder(mainActivity,ANDROID_CHANNEL_ID).setContentTitle("Notification").setContentText("Sample Text").
        setContentTitle("Sample Subject").setSmallIcon(R.mipmap.ic_launcher).build();
        notif.notify(0, notify);
    }
}

싱글톤 클래스의 주요 구조를 간단히 정리하면 다음과 같습니다.

  • private 생성자: 외부에서 인스턴스를 임의로 생성하지 못하도록 막습니다.
  • getInstance() 메서드: synchronized 키워드를 사용해 멀티스레드 환경에서도 항상 동일한 인스턴스만 반환하도록 보장합니다.
  • init() 메서드: 애플리케이션 컨텍스트를 한 번만 저장하여 어디서든 재사용할 수 있게 합니다.
  • notification() 메서드: Android 8.0(Oreo) 이상에서 필수인 알림 채널(Notification Channel)을 생성하고, 채널 설정(불빛, 진동, 잠금 화면 표시 여부 등)을 적용한 뒤 알림을 발송합니다.

5단계: 애플리케이션 실행

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 아이콘을 클릭하세요. 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기에 아래와 같은 기본 화면이 표시됩니다.

Android에서 싱글톤(Singleton) 패턴으로 알림(Notification) 구현하기

화면의 버튼을 클릭하면 싱글톤 클래스에서 생성된 알림이 아래와 같이 표시됩니다.

Android에서 싱글톤(Singleton) 패턴으로 알림(Notification) 구현하기

이처럼 싱글톤 패턴을 활용하면 애플리케이션 전체에서 하나의 인스턴스를 통해 알림 로직을 중앙 관리할 수 있어, 코드 중복을 줄이고 유지보수성을 크게 향상시킬 수 있습니다.