안드로이드 푸쉬메시지(FCM) 관련 잡다한 정보
그냥 나중에 또 고생 안 하려고 끄적이는 글이다.
혼자 삽질을 하루종일 한 결과로 알아낸 것들..
푸시 메시지(FCM)를 분기를 두자면 오레오 이전 버전과 이후 버전으로 나뉘게 되는데
두 개의 코드 차이가 있다..
나는 어느 버전이든 다 되게끔 하고 싶어서... 밤새면서 삽질을 했다.
(물론 공식 홈페이지에 다 나와있긴 한데.. 그래도 정리해서 보는 게 나을 거 같다.)
1. 오레오 이후 버전은 기본 채널을 설정해 줘야 한다는 것.
2. 오레오 이후 버전은 푸시 메시지 아이콘 이미지가 drawable가 들어갈 수 있지만 오레오 이전은 mipmap만 써야 한다는 것..
3. 오레오 이전 버전에선 Sound와 Priority만 넣어도 타 SNS처럼 알림이 오지만 오레오 이후 버전은 채널설정에 우선순위 높음까지 추가해줘야 SNS처럼 알림이 온다는 것.
4. FCM 설정하는 것보다 푸시 메시지 설정하는 게 더 힘들다는 것.
대체적으로 이렇다.
따로 로지컬 한 메시지 전송이 아닌 그냥 쉽게 전송하려면 파이어 베이스 홈페이지에 접속하여 메시지 전송만 하면 되지만.
나는 주문 관련에서 만들고 있었으므로. PHP에서 메시지를 전송해줘야 했다.
자 다음은 내가 위에것들을 적용한 푸시 메시지 코드이다.
솔직히 잘짠것도 아니고 그냥 급해서 이러니 저러니 짯던것이다.
틀린부분도 있을 수 있다.
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
32
33
34
35
36
37
|
private void sendNotification(String ContentTitle,String ContentText) {
System.out.println("Data"+ContentTitle+ContentText);
Intent intent = new Intent(this, booknuri.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
//알림메시지를 클릭하면 엑티비티 이동하게끔 만드는 특수 인텐트
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//안드로이드 기본 알림음 설정
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,"default");
//알림 설정 소리/타이틀/내용 등
notificationBuilder.setContentTitle("타이틀");
notificationBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
notificationBuilder.setContentText(ContentText);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(defaultSoundUri);
notificationBuilder.setFullScreenIntent(pendingIntent,true);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//오레오 이전버전과 이후버전의 셋팅
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationBuilder.setSmallIcon(R.drawable.booknurimain);
String channelName = getString(R.string.default_notification_channel_name);
NotificationChannel channel = new NotificationChannel("default", "기본 채널", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
} else {
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
그 다음은 중요한 PHP 에서 메시지를 보내주는 부분이다.
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
<?php
//fcm 전송 전 메시지 보낼 토큰값 가져오고 메시지 정리하는 함수
function fcm_msgReady($msg, $CID) {
global $connect;
$tokens = array();
$query = "테이블 접속 후 토큰값 가져오는 쿼리";
$result = mysqli_query($connect, $query);
while ($data = mysqli_fetch_array($result)) {
$tokens[] = $data['token'];
}
$message_string = $msg;
$message = array(
"title" => "주문이 접수되었습니다.",
"message" => $message_string,
);
fcm_sendNoti($tokens, $message);
}
//fcm 보내는 함수
function fcm_sendNoti($tokens, $message) {
global $connect;
$fields = array(
'registration_ids' => $tokens,
'data' => $message
);
$headers = array(
'Authorization:key = API_KEYS',
'Content-Type : application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
?>
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
PHP 부분은 이렇게 구성되어있어 메시지를 전송한다.
내가 만든 앱의 구성은 이렇다
로그인 -> DB에 토큰값 전송 후 저장 -> 로그아웃 -> 토큰값 제거
DB에서 토큰값 호출 -> PHP curl을 이용하여 FCM에 전달 -> 해당 토큰값을 가지고 있는 기기에 메시지 전송
되게 이것저것 뭔가 더있었지만.
이정도로 정리글을 마친다.
생각나는대로 써서 너무 뒤죽박죽이긴하다.
틀린부분이 있으면 피드백좀 부탁드리겠습니다.
저도 공부하는 입장이라..