2018. 7. 7. 17:48ㆍAndroid
1. 앱 구동시 FCM SDK에서 토큰 발행 및 서버에 저장(android)
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();
// 토큰 재생성
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String token = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "token = " + token);
sendTokenToServer(token);
}
private void sendTokenToServer(String token){
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("token", token)
.build();
Request request = new Request.Builder()
.url("서버URL") /* 서버에 발행된 토큰을 저장 */
.post(body)
.build();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. push.jsp / 푸시메시지 전송할 화면(spring / jsp)
<form action="/sendPush" method="post">
<input type="text" id="title" name="title"/>
<input type="text" id="content" name="content"/>
<input type="submit" value="push"/>
<input type="reset" value="cancel"/>
</form>
3. 푸시메시지 전송하기(spring / controller)
@RequestMapping(value ="/sendPush", method = {RequestMethod.GET,RequestMethod.POST})
public String sendPush(HttpServletRequest request, Model model) {
System.out.println("sendPush.......");
String token = getPushToken(); // 서버에 저장된 토큰 가져오기
String title = request.getParameter("title");
if(StringUtils.isEmpty(title)) title = "Push Default title";
String content = request.getParameter("content");
if(StringUtils.isEmpty(content)) title = "Push Default content";
try {
title = URLEncoder.encode(title ,"UTF-8"); // 한글깨짐으로 URL인코딩해서 보냄
content = URLEncoder.encode(content,"UTF-8");
System.out.println(String.format("title : %s, content : %s", title, content));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResponseEntity<String> result = sendHttp(token, title, content);
model.addAttribute("serverTime", token);
model.addAttribute("result", result.getBody());
return "push";
}
private ResponseEntity<String> sendHttp(String token, String title, String content){
RestTemplate template = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "key="+API_KEY); // API_KEY : Firebase 내 프로젝트의 서버키
JSONObject json = new JSONObject();
json.put("to", token);
JSONObject data = new JSONObject();
data.put("title" , title);
data.put("content", content);
json.put("data" ,data);
HttpEntity entity = new HttpEntity(json.toJSONString(), headers);
return template.exchange("https://fcm.googleapis.com/fcm/send", HttpMethod.POST, entity, String.class);
}
4. MyFirebaseMessagingService.class(android)
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.i(TAG, "onMessageReceived..");
Map<String, String> data = remoteMessage.getData();
String title = data.get("title");
String content = data.get("content");
try {
if(!TextUtils.isEmpty(title)) title = URLDecoder.decode(title,"UTF-8"); // 한글깨짐으로 서버에서 URLEncoding해서 보냄..
if(!TextUtils.isEmpty(content)) content = URLDecoder.decode(content,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.i(TAG, String.format("title : $s , content : %s",title,content));
sendNotification(title, content);
}
* https://fcm.googleapis.com/fcm/send로 보낼 때의 json 형태
{
"to": "etBbtvcHFZ4:APA91bF7I4BvHftRRpZ8qzA3by9kJJBSV2nT4_5vLkvk00-oKyyAXtFKxu2ybyJeTiTqoy4rTYOZzO6kkK74zqLFd5XCgO...",
"data": {
"title" : "title내용",
"content" : "content내용"
}
}
* 특정 단말에만 푸시 보낼 때 : json의 "to"에 단말 토큰 설정
* 모든 단말에 푸시 보낼 때 : json의 "to"에 "
/topics/all" 설정
(단, android에서 subscribeToTopic("all")로 설정되어 있어야 함.)
=> MainActivity.class(android)에서
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseMessaging.getInstance().subscribeToTopic("all");
if(FirebaseInstanceId.getInstance().getToken() != null)
Log.d(TAG+"_token : ",FirebaseInstanceId.getInstance().getToken());
}
https://smartstore.naver.com/byrollin?
'Android' 카테고리의 다른 글
원형 프로그레스바 (0) | 2018.07.12 |
---|---|
Notification (0) | 2018.07.07 |
FCM 푸시알림시 화면깨우기 (0) | 2018.07.07 |
FCM(Firebase Cloud Messaging) (0) | 2018.07.06 |
개선된 로딩 화면 (Splash Screen) (0) | 2018.07.02 |