Tencent Push Notification (QQ) 2020년 11월 서비스 종료
repositories {
google()
mavenCentral()
}
dependencies {
implementation 'com.nhncloud.android:nhncloud-push-fcm:1.9.5'
...
}
repositories {
google()
mavenCentral()
}
dependencies {
implementation 'com.nhncloud.android:nhncloud-push-adm:1.9.5'
...
}
buildscript {
// ...
dependencies {
// ...
classpath "com.google.gms:google-services:$google_services_version" // google-services plugin
}
}
allprojects {
// ...
repositories {
// ...
google() // Google's Maven repository
}
}
apply plugin: 'com.android.application'
android {
// ...
}
// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'
dependencies {
//...
compileOnly files('amazon/libs/amazon-device-messaging-1.2.0.jar')
}
-libraryjars amazon/libs/amazon-device-messaging-1.2.0.jar
-dontwarn com.amazon.device.messaging.**
-keep class com.amazon.device.messaging.** { *; }
-keep public class * extends com.amazon.device.messaging.ADMMessageReceiver
-keep public class * extends com.amazon.device.messaging.ADMMessageHandlerBase
-keep public class * extends com.amazon.device.messaging.ADMMessageHandlerJobBase
NhnCloudPushConfiguration configuration =
NhnCloudPushConfiguration.newBuilder(context, "YOUR_APP_KEY")
.build();
NhnCloudPush.initialize(PushType.FCM, configuration);
NhnCloudPushConfiguration configuration =
NhnCloudPushConfiguration.newBuilder(context, "YOUR_APP_KEY")
.build();
NhnCloudPush.initialize(PushType.ADM, configuration);
NhnCloudPush.initialize(NhnCloudPushConfiguration)는 Deprecated 되었습니다. NhnCloudPush.initialize(NhnCloudPushConfiguration)를 사용하여 초기화할 경우 PushType은 자동으로 FCM으로 설정됩니다.
public void onLogin(String userId) {
// Login.
NhnCloudSdk.setUserId(userId);
// 토큰 등록 등
}
// 수신 동의 설정 객체 생성
NhnCloudPushAgreement agreement = NhnCloudPushAgreement.newBuilder(true) // 알림 메시지 수신 동의
.setAllowAdvertisements(true) // 홍보성 알림 메시지 수신 동의
.setAllowNightAdvertisements(true) // 야간 홍보성 아림 메시지 수신 동의
.build();
// 토큰 등록 및 수신 동의 설정
NhnCloudPush.registerToken(context, agreement, new RegisterTokenCallback() {
@Override
public void onRegister(@NonNull PushResult result,
@Nullable String token) {
if (result.isSuccess()) {
// 토큰 등록 성공
} else {
// 토큰 등록 실패
int code = result.getCode();
String message = result.getMessage();
}
}
});
NhnCloudPush.queryTokenInfo(context, new QueryTokenInfoCallback() {
@Override
public void onQuery(@NonNull PushResult result,
@Nullable TokenInfo tokenInfo) {
if (result.isSuccess()) {
// 토큰 정보 조회 성공
String token = tokenInfo.getToken();
NhnCloudPushAgreement agreement = tokenInfo.getAgreement();
} else {
// 토큰 정보 조회 실패
int code = result.getCode();
String message = result.getMessage();
}
}
});
서비스 로그아웃 후에 메시지 수신을 원치 않으시면 토큰을 해제해야 합니다.
토큰이 해제되어도 단말기 상에 알림 권한은 회수되지 않습니다.
이미 해제된 토큰을 해제하면 "이미 해제된 토큰입니다(Already a token has been unregistered)" 라는 메시지와 함께 성공이 반환됩니다.
NhnCloudPush.unregisterToken(mContext, new UnregisterTokenCallback() {
@Override
public void onUnregister(@NonNull PushResult result,
@Nullable String unregisteredToken) {
if (result.isSuccess()) {
// 토큰 해제 성공시
} else {
// 토큰 해제 실패시
int code = result.getCode();
String message = result.getMessage();
}
}
});
Application#onCreate
에서 등록해야 합니다.메시지 수신 시 사용자가 앱을 사용 중(Foreground)일 경우 알림을 노출하지 않습니다. Foreground 여부는 OnReceiveMessageListener#onReceive 에 전달되는 isForeground 를 통해 확인 할 수 있습니다.
public class MyApplication extends Application {
@Override
public void onCreate() {
// ...
NhnCloudPush.setOnReceiveMessageListener(new OnReceiveMessageListener() {
@Override
public void onReceive(@NonNull NhnCloudPushMessage message,
boolean isForeground) {
// 사용자가 앱을 사용 중 일 때에도 알림을 노출
if (isForeground) {
NhnCloudNotification.notify(getApplicationContext(), message);
}
}
});
// ...
}
}
if (Build.VERSION.SDK_INT >= 33) {
NhnCloudNotification.requestPostNotificationsPermission(this, PERMISSION_REQUEST_CODE);
}
if (Build.VERSION.SDK_INT <= 32) {
NotificationChannel channel = NhnCloudNotification.getNotificationChannel(this);
if (channel == null) {
NhnCloudNotification.createNotificationChannel(this);
}
}
Application#onCreate
에서 등록해야 합니다.public class MyApplication extends Application {
@Override
public void onCreate() {
// ...
NhnCloudNotification.setOnClickListener(new OnClickListener() {
@Override
public void onClick(@NonNull NhnCloudPushMessage message) {
// 메시지 내용을 기반으로 페이지 이동 등의 서비스 로직 수행이 가능합니다.
Map<String, String> extras = message.getExtras();
}
});
// ...
}
}
Application#onCreate
에서 등록하거나 AndroidManifest.xml 파일에 메타 데이터로 정의할 수 있습니다.기본 알림 채널명을 설정하지 않으면 애플리케이션의 이름으로 자동 설정됩니다.
public class MyApplication extends Application {
@Override
public void onCreate() {
// ...
NhnCloudNotification.setDefaultChannelName(context, "YOUR_CHANNEL_NAME");
// ...
}
}
<!-- 기본 채널의 이름 설정 -->
<meta-data android:name="com.toast.sdk.push.notification.default_channel_name"
android:value="@string/default_notification_channel_name"/>
Application#onCreate
에서 등록하거나 AndroidManifest.xml 파일에 메타 데이터로 정의할 수 있습니다.전체 알림 옵션을 변경할 경우
public class MyApplication extends Application {
@Override
public void onCreate() {
// ...
NhnCloudNotificationOptions defaultOptions = new NhnCloudNotificationOptions.Builder()
.setPriority(NotificationCompat.PRIORITY_HIGH) // 알림 우선 순위 설정
.setColor(0x0085AA) // 알림 배경색 설정
.setLights(Color.RED, 0, 300) // LED 라이트 설정
.setSmallIcon(R.drawable.ic_notification) // 작은 아이콘 설정
.setSound(context, R.raw.dingdong1) // 알림음 설정
.setVibratePattern(new long[] {500, 700, 1000}) // 진동 패턴 설정
.enableVibration(true) // 진동 여부 설정
.enableForeground(true) // 포그라운드 알림 노출 설정
.enableBadge(true) // 배지 아이콘 사용 설정
.build();
NhnCloudNotification.setDefaultOptions(context, defaultOptions);
// ...
}
}
설정된 알림 옵션 중 일부만 변경할 경우
public class MyApplication extends Application {
@Override
public void onCreate() {
// ...
// 설정된 기본 알림 옵션 획득
NhnCloudNotificationOptions defaultOptions = NhnCloudNotification.getDefaultOptions(context);
// 알림 옵션 객체로부터 빌더 생성
NhnCloudNotificationOptions newDefaultOptions = defaultOptions.buildUpon()
.enableForeground(true) // 포그라운드 알림 노출 여부 설정만 변경
.build();
NhnCloudNotification.setDefaultOptions(context, newDefaultOptions);
// ...
}
}
<!-- 알림 우선 순위 -->
<meta-data android:name="com.toast.sdk.push.notification.default_priority"
android:value="1"/>
<!-- 알림 배경색 -->
<meta-data android:name="com.toast.sdk.push.notification.default_background_color"
android:resource="@color/defaultNotificationColor"/>
<!-- LED 라이트 -->
<meta-data android:name="com.toast.sdk.push.notification.default_light_color"
android:value="#0000ff"/>
<meta-data android:name="com.toast.sdk.push.notification.default_light_on_ms"
android:value="0"/>
<meta-data android:name="com.toast.sdk.push.notification.default_light_off_ms"
android:value="500"/>
<!-- 작은 아이콘 -->
<meta-data android:name="com.toast.sdk.push.notification.default_small_icon"
android:resource="@drawable/ic_notification"/>
<!-- 알림음 -->
<meta-data android:name="com.toast.sdk.push.notification.default_sound"
android:value="notification_sound"/>
<!-- 진동 패턴 -->
<meta-data android:name="com.toast.sdk.push.notification.default_vibrate_pattern"
android:resource="@array/default_vibrate_pattern"/>
<!-- 진동 여부 설정 -->
<meta-data android:name="com.toast.sdk.push.notification.vibration_enabled"
android:resource="true"/>
<!-- 배지 아이콘 사용 -->
<meta-data android:name="com.toast.sdk.push.notification.badge_enabled"
android:value="true"/>
<!-- 앱 실행 중 알림 노출 -->
<meta-data android:name="com.toast.sdk.push.notification.foreground_enabled"
android:value="false"/>
유형 | 기능 | 액션 |
---|---|---|
앱 열기 (OPEN_APP) | 애플리케이션 실행 | PushAction.ActionType.OPEN_APP |
URL 열기 (OPEN_URL) | URL로 이동 (웹 URL 주소 혹은 앱 커스텀 스킴 실행) |
PushAction.ActionType.OPEN_URL |
답장 (REPLY) | 알림에서 답장 전송 | PushAction.ActionType.REPLY |
취소 (DISMISS) | 현재 알림 취소 | PushAction.ActionType.DISMISS |
버튼은 메시지당 최대 3개까지 지원합니다.
웹 URL 사용시 미디어 파일 다운로드 시간이 소요됩니다.
사용된 이미지가 1:1 비율이 아닌 경우 강제로 1:1로 변경되기 때문에 기대와 다른 이미지가 노출될 수 있습니다.
Application#onCreate
에서 등록해야 합니다.public class MyApplication extends Application {
@Override
public void onCreate() {
// ...
NhnCloudNotification.setOnActionListener(new OnActionListener() {
@Override
public void onAction(@NonNull PushAction action) {
// 답장 액션일 경우, 서비스 서버로 해당 내용을 전송
if (action.getActionType() == PushAction.ActionType.REPLY) {
// 사용자가 입력한 답장 내용 획득
String userText = action.getUserText();
// 서비스 서버로 사용자 입력 내용 전송
}
}
});
// ...
}
}
(주의) 1. onMessageReceived 함수에서 메시지 수신 후 알림 노출을 요청(notify)하지 않으면 알림이 노출되지 않습니다. 2. 알림을 직접 생성할 경우 Push 서비스 인텐트를 알림의 콘텐츠 인텐트로 설정해야만 지표 수집이 가능합니다. (아래 지표 수집 기능 추가 섹션 참고)
public class MyPushMessageReceiver extends NhnCloudPushMessageReceiver {
@Override
public void onMessageReceived(@NonNull Context context,
@NonNull NhnCloudRemoteMessage remoteMessage) {
// 채널 아이디 변경
remoteMessage.setChannelId("channel");
// 메시지 내용 수정
NhnCloudPushMessage message = remoteMessage.getMessage();
CharSequence title = message.getTitle();
message.setTitle("[Modified] " + title);
// 실행 인텐트 설정 (미설정시 패키지 기본 메인 액티비티 실행)
Intent launchIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(
context,
REQUEST_CODE,
launchIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
// 사용자가 앱을 사용중일때와 그렇지 않을때를 구분하여 알림을 노출하고 싶은 경우
if (!isAppForeground()) {
// 알림 생성 및 노출
notify(context, remoteMessage, contentIntent);
} else {
// 특정 UI 화면 노출
NhnCloud.makeText(context, message.title, NhnCloud.LENGTH_SHORT).show();
}
}
}
(주의) 1. NhnCloudPushMessageReceiver를 사용하는 경우, 반드시 permission을 설정해야 합니다. 2. API 레벨 31 이상 타기팅 시 exported 속성을 설정해야 합니다.
<manifest>
<application>
<receiver android:name=".NhnCloudPushSampleReceiver"
android:permission="${applicationId}.toast.push.permission.RECEIVE"
android:exported="false">
<intent-filter>
<action android:name="com.toast.android.push.MESSAGE_EVENT" />
</intent-filter>
</receiver>
<!-- 생략 -->
</application>
<!-- 생략 -->
</manifest>
public class MyPushMessageReceiver extends NhnCloudPushMessageReceiver {
private NotificationManager mManager = null;
@Override
public void onMessageReceived(
@NonNull Context context,
@NonNull NhnCloudRemoteMessage remoteMessage) {
// 메시지 내용 획득
NhnCloudPushMessage message = remoteMessage.getMessage();
//NotificationManager 생성
if (mManager == null) {
mManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (mManager == null) {
Log.e(TAG, "Failed to get NotificationManager");
return;
}
}
// 채널 설정
String channelId = "YOUR_CHANNEL_ID";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = mManager.getNotificationChannel(channelId);
if (channel == null) {
String channelName = "YOUR_CHANNEL_NAME";
createNotificationChannel(channelId, channelName);
}
}
// 실행 인텐트 설정
Intent launchIntent = new Intent(context, MainActivity.class);
// 지표 전송을 포함한 컨텐츠 인텐트 생성
PendingIntent contentIntent;
contentIntent = getContentIntent(context, remoteMessage, launchIntent);
//알림 생성
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId);
builder.setContentTitle(message.getTitle())
.setContentText(message.getBody())
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(contentIntent)
.setAutoCancel(true);
notify(context, NotificationUtils.createNewId(), builder.build());
}
...
}
(주의) 기기에서 지원하지 않는 emoji를 사용한 경우, 표시되지 않을 수 있습니다.
// 추가할 태그 아이디 목록 생성
Set<String> tagIds = new HashSet<>();
tagIds.add(TAG_ID_1); // e.g. "ZZPP00b6" (8자리 문자열)
tagIds.add(TAG_ID_2);
// 로그인되어 있는 사용자 아이디의 태그 아이디 목록 추가
NhnCloudPush.addUserTag(tagIds, new UserTagCallback() {
@Override
public void onResult(@NonNull PushResult result, @Nullable Set<String> tagIds) {
if (result.isSuccess()) {
// 사용자 태그 아이디 추가 성공
} else {
// 사용자 태그 아이디 추가 실패
int errorCode = result.getCode();
String errorMessage = result.getMessage();
}
}
});
// 로그인되어 있는 사용자 아이디의 태그 아이디 목록 업데이트 (기존 태그 아이디 목록은 삭제되고 입력한 값으로 설정)
NhnCloudPush.setUserTag(tagIds, new UserTagCallback() {
@Override
public void onResult(@NonNull PushResult result, @Nullable Set<String> tagIds) {
if (result.isSuccess()) {
// 사용자 태그 아이디 목록 업데이트 성공
} else {
// 사용자 태그 아이디 목록 업데이트 실패
int errorCode = result.getCode();
String errorMessage = result.getMessage();
}
}
});
// 로그인되어 있는 사용자 아이디의 전체 태그 아이디 목록을 반환
NhnCloudPush.getUserTag(new UserTagCallback() {
@Override
public void onResult(@NonNull PushResult result, @Nullable Set<String> tagIds) {
if (result.isSuccess()) {
// 사용자 태그 아이디 목록 획득 성공
} else {
// 사용자 태그 아이디 목록 획득 실패
int errorCode = result.getCode();
String errorMessage = result.getMessage();
}
}
});
// 삭제할 태그 아이디 목록 생성
Set<String> tagIds = new HashSet<>();
tagIds.add(TAG_ID_1); // e.g. "ZZPP00b6" (8자리 문자열)
tagIds.add(TAG_ID_2);
// 로그인되어 있는 사용자 아이디의 태그 아이디 목록 삭제
NhnCloudPush.removeUserTag(tagIds, new UserTagCallback() {
@Override
public void onResult(@NonNull PushResult result, @Nullable Set<String> tagIds) {
if (result.isSuccess()) {
// 사용자 태그 아이디 목록 삭제 성공
} else {
// 사용자 태그 아이디 목록 삭제 실패
int errorCode = result.getCode();
String errorMessage = result.getMessage();
}
}
});
// 로그인되어 있는 사용자 아이디의 전체 태그 아이디 목록 삭제
NhnCloudPush.removeAllUserTag(new UserTagCallback() {
@Override
public void onResult(@NonNull PushResult result, @Nullable Set<String> tagIds) {
if (result.isSuccess()) {
// 전체 사용자 태그 삭제 성공
} else {
// 전체 사용자 태그 삭제 실패
int errorCode = result.getCode();
String errorMessage = result.getMessage();
}
}
});
/* NhnCloudPushConfiguration.java */
public String getAppKey();
public static Builder newBuilder(@NonNull Context context, @NonNull String appKey);
Method | Returns | |
---|---|---|
getAppKey | String | Push 서비스 앱 키를 반환합니다. |
static newBuilder | NhnCloudPushConfiguration.Builder | NhnCloudPushConfiguration 객체 생성을 위한 빌더를 생성합니다. |
/* PushResult.java */
public int getCode();
public String getMessage();
public boolean isSuccess();
public boolean isFailure();
Method | Returns | |
---|---|---|
getCode | int | 결과 코드를 반환합니다. |
getMessage | int | 결과 메시지를 반환합니다. |
isSuccess | boolean | 성공 여부를 반환합니다. |
isFailure | boolean | 실패 여부를 반환합니다. |
/* TokenInfo.java */
public String getPushType();
public NhnCloudPushAgreement getAgreement();
public String getTimeZone();
public String getCountry();
public String getLanguage();
public String getUserId();
public Date getActivatedDateTime();
public String getToken();
Method | Returns | |
---|---|---|
getPushType | String | Push 타입을 반환합니다. |
getAgreement | NhnCloudPushAgreement | 알림/광고/야간 광고 등 동의 여부를 반환합니다. |
getTimeZone | String | 타임존을 반환합니다. |
getCountry | String | 국가 코드를 반환합니다. |
getLanguage | String | 언어 코드를 반환합니다. |
getUserId | String | 사용자 ID를 반환합니다. |
getActivatedDateTime | Date | 토큰의 최근 등록 일시를 반환합니다. |
getToken | String | 토큰을 반환합니다. |
/* NhnCloudRemoteMessage.java */
public String getChannelId();
public void setChannelId(String channelId);
public NhnCloudPushMessage getMessage();
public String getSenderId();
Method | Returns | |
---|---|---|
getChannelId | String | 채널 ID를 반환합니다. |
setChannelId | 채널 ID를 설정합니다. | |
getMessage | NhnCloudPushMessage | 메시지 객체를 반환합니다. |
getSenderId | String | 발신자 ID를 반환합니다. (FCM Only) |
/* NhnCloudPushMessage.java */
public String getMessageId();
public String getPusyType();
public String getTitle();
public void setTitle(String title);
public String getBody();
public void setBody(String body);
public RichMessage getRichMessage();
public Map<String, String> getExtras();
Method | Returns | |
---|---|---|
getMessageId | String | 메시지 식별자를 반환합니다. |
getPusyType | String | PushType을 반환합니다. |
getTitle | String | 메시지 타이틀을 반환합니다. |
setTitle | 메시지 타이틀을 설정합니다. | |
getBody | String | 메시지 내용을 반환합니다. |
setBody | 메시지 내용을 설정합니다. | |
getRichMessage | RichMessage | 리치 메시지 정보를 반환합니다. |
getExtras | 수신된 메시지 전체를 반환합니다. |
/* PushAction.java */
public ActionType getActionType();
public String getNotificationId();
public String getNotificationChannel();
public NhnCloudPushMessage getMessage();
public String getUserText();
Method | Returns | |
---|---|---|
getActionType | ActionType | ActionType을 반환합니다. |
getNotificationId | String | 액션이 실행된 알림의 ID을 반환합니다. |
getNotificationChannel | String | 액션이 실행된 알림의 채널을 반환합니다. |
getMessage | NhnCloudPushMessage | 액션이 실행된 알림의 메시지 정보를 반환합니다. |
getUserText | RichMessage | 사용자가 입력한 문자열을 반환합니다. |
/* NhnCloudPushMessageReceiver.java */
public final boolean isAppForeground();
public final void notify(Context context, NhnCloudRemoteMessage message);
public final void notify(Context context, NhnCloudRemoteMessage message, PendingIntent contentIntent);
public final void notify(Context context, int notificationId, Notification notification);
@Deprecated
public final PendingIntent getNotificationServiceIntent(Context context, NhnCloudRemoteMessage message, PendingIntent contentIntent);
public final PendingIntent getContentIntent(Context context, NhnCloudRemoteMessage message, Intent launchIntent);
Method | Returns | Parameters | |
---|---|---|---|
isAppForeground | boolean | 현재 앱을 사용중인지 여부를 반환합니다. | |
notify | Context, NhnCloudRemoteMessage | 기본 실행 인텐트로 알림을 생성 및 노출합니다. | |
notify | Context, NhnCloudRemoteMessage, PendingIntent | 사용자 실행 인텐트로 알림을 생성 및 노출합니다. | |
notify | Context, int, Notification | 사용자 알림을 특정 ID로 노출합니다. | |
@Deprecated getNotificationServiceIntent |
PendingIntent | Context, NhnCloudRemoteMessage, PendingIntent | 지표 전송을 포함하는 사용자 실행 인텐트를 반환합니다. Android 12 (API 레벨 31) 이상부터 정상 동작 하지 않으며, 대신 getContentIntent()를 사용해야 합니다. |
getContentIntent | PendingIntent | Context, NhnCloudRemoteMessage, Intent | 지표 전송을 포함하는 사용자 실행 인텐트를 반환합니다. |
/* NhnCloudNotificationOptions.java */
public int getPriority();
public int getSmallIcon();
public int getColor();
public int getLightColor();
public int getLightOnMs();
public int getLightOffMs();
public long[] getVibratePattern();
public Uri getSound();
public boolean isVibrationEnabled();
public boolean isForegroundEnabled();
public boolean isBadgeEnabled();
public Builder buildUpon();
Method | Returns | Parameters | |
---|---|---|---|
getPriority | int | 우선 순위를 반환합니다. | |
getSmallIcon | int | 작은 아이콘의 리소스 식별자를 반환합니다. | |
getColor | int | 배경색을 반환합니다. | |
getLightColor | int | LED 색을 반환합니다. | |
getLightOnMs | int | LED 불이 들어올 때의 시간을 반환합니다. | |
getLightOffMs | int | LED 불이 나갈 때의 시간을 반환합니다. | |
getVibratePattern | long[] | 진동의 패턴을 반환합니다. | |
getSound | Uri | 알림음의 Uri 를 반환합니다. | |
isVibrationEnabled | boolean | 진동 여부를 반환합니다. | |
isForegroundEnabled | boolean | 포그라운드 알림 사용 여부를 반환합니다. | |
isBadgeEnabled | boolean | 배지 아이콘 사용 여부를 반환합니다. | |
buildUpon | NhnCloudNotificationOptions#Builder | 현재 옵션 정보를 기반으로 빌더를 반환합니다. |