이 예제는 Android 앱에서 푸시 알림을 수신할 때 새로운 알림(Notification)을 추가하는 방법을 보여줍니다. 단계별로 따라 하면 버튼 클릭 한 번으로 새로운 알림을 생성하는 기능을 구현할 수 있습니다.
1단계 — 새 프로젝트 생성
Android Studio에서 File → New Project를 선택하고, 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 새 프로젝트를 만듭니다.
2단계 — 레이아웃 파일 작성
다음 코드를 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"
tools:context=".MainActivity">
<Button
android:onClick="createNotification"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="16dp"
android:text="Create notification" />
</RelativeLayout>화면 중앙에 배치된 하나의 버튼이며, 이 버튼을 클릭하면 createNotification() 메서드가 호출되어 새로운 알림이 생성됩니다.
3단계 — MainActivity 코드 작성
다음 코드를 src/MainActivity.java에 추가합니다.
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onNewIntent(getIntent());
}
public void createNotification(View view) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id);
mBuilder.setContentTitle("Notify Me");
mBuilder.setContentText("Something important!");
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
mBuilder.setAutoCancel(true);
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());
}
}코드 핵심 포인트
- 알림 채널(Notification Channel): Android 8.0(Oreo, API 26)부터는 모든 알림이 반드시 채널에 할당되어야 합니다. 위 코드에서는 SDK 버전을 확인한 후 채널을 생성합니다.
- 고유한 알림 ID:
System.currentTimeMillis()를 ID로 사용하면 알림이 호출될 때마다 서로 다른 새 알림으로 표시됩니다. 고정된 ID를 사용하면 기존 알림이 덮어써지므로 주의해야 합니다. - setAutoCancel(true): 사용자가 알림을 탭하면 자동으로 알림이 사라집니다.
4단계 — 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>
</application>
</manifest>진동 효과를 위해 VIBRATE 권한을 선언하는 것도 잊지 마세요.
앱 실행 및 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 스마트폰을 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭합니다. 실행 옵션에서 자신의 모바일 기기를 선택하면, 기본 화면이 표시된 앱이 기기에서 실행됩니다.
앱 화면 중앙의 Create notification 버튼을 누를 때마다 새로운 알림이 상태 표시줄에 계속 추가되는 것을 확인할 수 있습니다. 각 알림은 서로 다른 ID를 가지므로 하나의 알림이 다른 알림을 대체하지 않고 개별적으로 쌓입니다.