이 튜토리얼에서는 앱이 완전히 종료된 상태에서도 안드로이드 알림을 계속 받을 수 있도록 구현하는 방법을 단계별로 알아봅니다. 핵심 원리는 액티비티가 화면에서 사라질 때 백그라운드 서비스(Service)를 시작하고, 해당 서비스가 주기적으로 알림을 생성하도록 만드는 것입니다.
구현 개요
앱이 닫히거나 백그라운드로 전환될 때 onStop() 콜백에서 서비스를 실행하고, 서비스 내부의 타이머(Timer)가 일정 간격으로 알림을 발송하도록 구성합니다. 이를 위해 다음 세 가지 요소가 필요합니다.
- 알림을 발생시키는 버튼이 있는 메인 액티비티
- 주기적으로 알림을 생성하는 백그라운드 서비스
- 서비스 등록 및 진동 권한이 포함된 매니페스트 파일
1단계: 새 프로젝트 생성
Android Studio에서 File → New Project를 선택하고, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.
2단계: 레이아웃 작성 (activity_main.xml)
res/layout/activity_main.xml에 아래 코드를 추가합니다. 화면 중앙에 알림 테스트용 버튼 하나를 배치하는 단순한 구조입니다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="closeApp"
android:text="close App for notification" />
</RelativeLayout>3단계: 메인 액티비티 구현 (MainActivity.java)
src/MainActivity.java에 다음 코드를 추가합니다. 여기서 중요한 부분은 onStop() 메서드입니다. 앱이 화면에서 사라지는 시점에 NotificationService를 시작시켜, 앱이 닫힌 후에도 알림이 동작하도록 만듭니다.
package app.tutorialspoint.com.notifyme;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStop() {
super.onStop();
// 앱이 화면에서 사라질 때 알림 서비스를 시작합니다.
startService(new Intent(this, NotificationService.class));
}
public void closeApp(View view) {
finish();
}
}4단계: 알림 서비스 구현 (NotificationService.java)
src/NotificationService.java에 아래 코드를 추가합니다. 이 서비스는 Timer와 TimerTask를 사용해 설정된 주기(예제에서는 5초)마다 알림을 생성합니다. 또한 안드로이드 8.0(오레오, API 26) 이상에서 필수인 알림 채널(Notification Channel) 생성 로직도 포함되어 있습니다.
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
public class NotificationService extends Service {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
Timer timer;
TimerTask timerTask;
String TAG = "Timers";
int Your_X_SECS = 5; // 알림 반복 주기(초)
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
@Override
public void onCreate() {
Log.e(TAG, "onCreate");
}
@Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
stopTimerTask();
super.onDestroy();
}
// TimerTask 내부에서 UI 관련 처리를 하기 위한 Handler
final Handler handler = new Handler();
public void startTimer() {
timer = new Timer();
initializeTimerTask();
// 5초 후 첫 알림, 이후 Your_X_SECS 초마다 반복
timer.schedule(timerTask, 5000, Your_X_SECS * 1000);
}
public void stopTimerTask() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
createNotification();
}
});
}
};
}
private void createNotification() {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), default_notification_channel_id);
mBuilder.setContentTitle("My Notification");
mBuilder.setContentText("Notification Listener Service Example");
mBuilder.setTicker("Notification Listener Service Example");
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
mBuilder.setAutoCancel(true);
// 안드로이드 오레오(API 26) 이상에서는 알림 채널이 필요합니다.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
}
}5단계: 매니페스트 설정 (AndroidManifest.xml)
AndroidManifest.xml에 진동 권한과 함께 서비스를 등록합니다. 서비스가 정상적으로 동작하려면 매니페스트에 반드시 선언되어야 합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.tutorialspoint.com.notifyme">
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".NotificationService"
android:label="@string/app_name">
<intent-filter>
<action
android:name="app.tutorialspoint.com.notifyme.NotificationService" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
</application>
</manifest>앱 실행 및 테스트
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면, 기본 화면이 표시된 앱이 기기에 설치·실행됩니다.
버튼을 눌러 앱을 종료하거나 홈 버튼으로 화면을 벗어나면, 몇 초 후부터 설정한 주기마다 알림이 도착하는 것을 확인할 수 있습니다. 이처럼 onStop()에서 서비스를 시작하는 방식만으로도 앱이 닫힌 상태에서 알림을 지속적으로 받을 수 있습니다.
참고 사항
- 안드로이드 최신 버전에서는 배터리 최적화 정책으로 인해 백그라운드 서비스가 강제 종료될 수 있습니다. 실무에서는 Foreground Service나 WorkManager 사용을 권장합니다.
- 알림 반복 주기(
Your_X_SECS) 값을 변경하여 원하는 간격으로 알림을 조정할 수 있습니다.