마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

push notification 클릭시 해당 activity로 이동하면서 db만 다르게 출력하려면?

0 추천
fcm 으로 push notification을 구현하고 있는데..

 

 

예를 들어 notification을 클릭해서 이동하려는 Activity가 채팅방이라면

수많은 채팅방중에 어떤 채팅방DB를 가져와야 하는지

key값 같은 것을 알려줘야 하는데

그걸 push로 어떻게 보내나요?

 

 

그리고 그걸 받았을 때

onMessageReceived() 에서

notification 울리기 전에

remoteMessage안의 그 값을 intent에 넣어서 pendingIntent로 감싸서 넘겨주는 게 맞나요?
목마른어린양 (960 포인트) 님이 2017년 6월 30일 질문

2개의 답변

+1 추천
 
채택된 답변
이미 어느 정도 아시니 예를 들어 설명합니다. 아래 코드는 실제 서비스 중인 코드의 일부입니다.

제가 FCM으로 데이터를 보내는 서버 코드의 일부입니다. (제 서비스 중에 자전거를 발견했을 때, 주인에게 알려주는 코드입니다.)

FCMdata fcmData = new FCMdata();
fcmData.to = theUser.FCM_Token;
FCMdataBody fcmBody = new FCMdataBody();

fcmBody.msg_type = "FOUND";
fcmBody.title = "제목";
fcmBody.msg = "자전거 발견";
fcmBody.data = bikeLost.nickname + "_" + bikeLost.location_lost + "_" +
                bikeLost.dt_lost;
fcmData.data = fcmBody;

상기 data 필드에 원하는 데이터를 넣어서 내려 주면,

앱에서 data 필드를 아래 listData로 파싱해서 가지니다.
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
    String title = remoteMessage.getData().get("title");
    String msgType = remoteMessage.getData().get("msg_type");
    String msg = remoteMessage.getData().get("msg");
    String data = remoteMessage.getData().get("data");
    String[] listData = data.split("_");

    if (msgType.equalsIgnoreCase("LOST")) {
        if (listData.length > 2) {
        // 분실신고에 대한 처리 로직 처리
        }
    } else if (msgType.equalsIgnoreCase("LOSTCANCEL")) {
        if (listData.length > 2) {
        // 분실 취소
        }
    } else if (msgType.equalsIgnoreCase("FOUND")) {
        if (listData.length > 2) {
            showFoundNotification(title, msg, listData[0]);
        }
    } else {
    // 기타..
    }
}

showFoundNotification은 다음과 같습니다.
질문하신 것처럼 PendingIntent를 보내면 됩니다.

private void showFoundNotification(String messageTitle, String messageBody, String nickName) {
    Intent intent = new Intent(this, ProtectionLocation.class); // 보내고자 하는 Activity
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("NickName", nickName); // 전달하고자 하는 데이터.
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_app)
            .setContentTitle(messageTitle)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
Will Kim (43,170 포인트) 님이 2017년 6월 30일 답변
목마른어린양님이 2017년 7월 20일 채택됨
설명보충:
Activity를 실행할 때 전달하고자 하는 데이터는 intent.putExtra를 이용해서 보내면 됩니다. 여러개면 여러개, 그러면 노티피케이션을 터치 했을때, 해당 데이터가 원하는 액티비티로 전달됩니다.
상세한 설명 감사합니다. ^0^ 복 받으실 거에요.

FCMdata와 FCMdataBody는 단순 Data Class인거죠?
fcmData안에 다 넣고나서
그걸 어떤 방식으로 보내셨는지..
제 소스와 달라서 좀 이해가 안 되요...


제 코딩은 JSONObject안에 다 넣어서
HttpURLConnection 으로 보내는 코딩입니다.(이 글 마지막부분에 첨부)



그리고 받는 부분에서도
저는 remoteMessage.getNotification.getBody()
이렇게 getNotification으로 받는데

remoteMessage.getData() 값은 null이 나옵니다.



아무래도 처음에 push 보내는 부분의 코딩이 좀 다른거 같은데 그 부분 소스를 좀 보여주실 수 있으신가요? ^^;
그것만 보면 정확히 이해할 수 있을 것 같습니다.


혹여 안 보여주신다고 해도 답변은 정말 감사히 잘 봤습니다.
많은 도움이 됐습니다.
대단히 감사합니다. ^^



<푸쉬 보내는 소스>---------------------------------------------------
try {
                                    // FMC 메시지 생성 start
                                    JSONObject root = new JSONObject();
                                    JSONObject notification = new JSONObject();
                                    notification.put("body", message);
                                    notification.put("title", "titleTest");
                                    root.put("notification", notification);
                                    root.put("to", user.getFcmToken());
                                    // FMC 메시지 생성 end

                                    URL Url = new URL(MyStr.FCM_MESSAGE_URL);

                                    HttpURLConnection conn = (HttpURLConnection) Url.openConnection();
                                    conn.setRequestMethod("POST");
                                    conn.setDoOutput(true);
                                    conn.setDoInput(true);
                                    conn.addRequestProperty("Authorization", "key=" + MyStr.SERVER_KEY);
                                    conn.setRequestProperty("Accept", "application/json");
                                    conn.setRequestProperty("Content-type", "application/json");

                                    OutputStream os = conn.getOutputStream();
                                    os.write(root.toString().getBytes("utf-8"));
                                    os.flush();
                                    conn.getResponseCode();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
0 추천

상세한 설명 감사합니다 ^^

bullet force

 

익명사용자 님이 2017년 6월 30일 답변
...