2016-06-01 2 views
12

새 Firebase 서비스로 내 Android 장치에 푸시 알림을 보내려고합니다. 앱을 등록하고 설정했으며, 알림을 수신하는 데 필요한 모든 코드를 Android 앱에 넣었습니다. Firebase Console을 통해 내 앱에 알림을 보내고받을 수 있습니다. 이제 Java 독립형 서버를 작성하여 모든 장치에 알림을 보내려고합니다. 이것은 내 현재 코드 :Firebase Java 서버가 모든 장치에 푸시 알림을 전송합니다.

final String apiKey = "I added my key here"; 
URL url = new URL("https://fcm.googleapis.com/fcm/send"); 
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
conn.setDoOutput(true); 
conn.setRequestMethod("POST"); 
conn.setRequestProperty("Content-Type", "application/json"); 
conn.setRequestProperty("Authorization", "key=" + apiKey); 

conn.setDoOutput(true); 

String input = "{\"notification\" : {\"title\" : \"Test\"}, \"to\":\"test\"}"; 

OutputStream os = conn.getOutputStream(); 
os.write(input.getBytes()); 
os.flush(); 
os.close(); 

int responseCode = conn.getResponseCode(); 
System.out.println("\nSending 'POST' request to URL : " + url); 
System.out.println("Post parameters : " + input); 
System.out.println("Response Code : " + responseCode); 

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
String inputLine; 
StringBuffer response = new StringBuffer(); 

while ((inputLine = in.readLine()) != null) { 
    response.append(inputLine); 
} 
in.close(); 

// print result 
System.out.println(response.toString()); 

그리고 이것이 내가 그들의 서버에서 다시 얻고 결과 : 간단하게 태그가 나는 작동하지 않습니다 "를"제거, 불행하게도

{"multicast_id":6602141464107786356,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]} 

코드 400이 반환되었습니다. 장치를 등록하고 장치 ID를 서버에 보내고 저장 한 다음 서버에 등록 된 모든 장치를 루프하여 메시지를 보내야한다고 읽었습니다. 콘솔과 마찬가지로 모든 장치에 메시지를 보내는 더 쉬운 방법은 없습니까?

당신의 도움이 정말려고 되었기 때문에이 하루 종일 일을, 감사 길이 = (

감사합니다, 더스틴

나는이 가능하다 생각하지 않는다

답변

11

. 대신 내가 동일한 주제에 대한 모든 장치를 등록한다 제안 다음은 다음은이에 대한 도움말 문서를 한 번에 메시지를 모든 장치입니다 수 있습니다.

는 서버에서 주제 메시지 보내기

https://firebase.google.com/docs/cloud-messaging/topic-messaging

+0

그래, 나는 이런 식으로 생각했다.하지만 앱 자체에 등록 코드를 쓰고 싶지는 않다 ... 그게 어떻게 든 가능하다면 어떤 생각이 들겠 니? – user3907491

+3

앱에 등록 코드가 있다는 것은 무엇을 의미합니까? 사용자가 앱을 시작하면 자동으로 주제에 등록 할 수 있습니다. Android에서는, 'FirebaseMessaging.getInstance(). subscribeToTopic ("allDevices");'이것을 onCreate 메소드에 넣으면 앱이 시작될 때 자동으로 등록됩니다. –

+0

대단히 감사합니다. 그게 바로 제가 찾고있는 것입니다 =) 어떻게 답을 가장 좋은 것으로 표시 할 수 있습니까? 이미 +1했습니다. – user3907491

1

안드로이드 클라이언트 측 코드는 다음과 같아야합니다

//subscribe_topic with name "ALL" 
FirebaseMessaging.getInstance().subscribeToTopic("ALL");  

서버 측 :이 솔루션은 사용 중포 기지 아파치 HttpClient를 푸시 알림을 보내

string json = "{\"to\": \"/topics/ALL\",\"data\": {\"message\": \"This is a Cloud Messaging Topic Message\",}}"; 
6

:

HttpClient client = HttpClientBuilder.create().build(); 
HttpPost post = new HttpPost("https://fcm.googleapis.com/fcm/send"); 
post.setHeader("Content-type", "application/json"); 
post.setHeader("Authorization", "key=AIzaSyBSxxxxsXevRq0trDbA9mhnY_2jqMoeChA"); 

JSONObject message = new JSONObject(); 
message.put("to", "dBbB2BFT-VY:APA91bHrvgfXbZa-K5eg9vVdUkIsHbMxxxxxc8dBAvoH_3ZtaahVVeMXP7Bm0iera5s37ChHmAVh29P8aAVa8HF0I0goZKPYdGT6lNl4MXN0na7xbmvF25c4ZLl0JkCDm_saXb51Vrte"); 
message.put("priority", "high"); 

JSONObject notification = new JSONObject(); 
notification.put("title", "Java"); 
notification.put("body", "Notificação do Java"); 

message.put("notification", notification); 

post.setEntity(new StringEntity(message.toString(), "UTF-8")); 
HttpResponse response = client.execute(post); 
System.out.println(response); 
System.out.println(message); 
+0

'HttpClientBuilder를 확인할 수 없습니다.'라는 오류가 발생합니다. 오류를 수정하려면 어떻게해야합니까? – Peter

+0

maven 의존성을 추가 했습니까? org.apache.httpcomponents HttpClient를 \t 4.5.2 Geucimar

+0

정확히''가치'message' "로"무엇? – tomasb

1
@Autowired 
AndroidPushNotificationsService androidPushNotificationsService; 

@RequestMapping(value = "/send", method = RequestMethod.GET, produces = "application/json") 
public ResponseEntity<String> send() { 


    JSONObject body = new JSONObject(); 
    // JsonArray registration_ids = new JsonArray(); 
    // body.put("registration_ids", registration_ids); 
    body.put("to", "xxxxxxxxxxxxxxxxxxxjPwZpLgLpji_"); 
    body.put("priority", "high"); 
    // body.put("dry_run", true); 

    JSONObject notification = new JSONObject(); 
    notification.put("body", "body string here"); 
    notification.put("title", "title string here"); 
    // notification.put("icon", "myicon"); 

    JSONObject data = new JSONObject(); 
    data.put("key1", "value1"); 
    data.put("key2", "value2"); 

    body.put("notification", notification); 
    body.put("data", data); 

    HttpEntity<String> request = new HttpEntity<>(body.toString()); 

    CompletableFuture<FirebaseResponse> pushNotification = androidPushNotificationsService.send(request); 
    CompletableFuture.allOf(pushNotification).join(); 

    try { 
     FirebaseResponse firebaseResponse = pushNotification.get(); 
     if (firebaseResponse.getSuccess() == 1) { 
      log.info("push notification sent ok!"); 
     } else { 
      log.error("error sending push notifications: " + firebaseResponse.toString()); 
     } 
     return new ResponseEntity<>(firebaseResponse.toString(), HttpStatus.OK); 

    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } catch (ExecutionException e) { 
     e.printStackTrace(); 
    } 
    return new ResponseEntity<>("the push notification cannot be send.", HttpStatus.BAD_REQUEST); 
} 

당신 여기에서 수업을받을 수 있습니다 : https://github.com/AndreiD/testingpushnotifications

+0

코드를 확인했지만 내가하지 않은 것은 무엇인가요? 이해가 왜'''HeaderRequestInterceptor'''를 쓰는 반면'''HttpHeaders''' 만 사용하여 헤더를 설정하고'''HttpEntity'''에 넣을 수 있습니다. – zt1983811

3

코드가 완벽합니다. 알림을 보내는 사용자의 등록 ID를 다시 확인하기 만하면됩니다. to 대신 users 디바이스 regid를 사용하십시오. 그것은 나를 위해 완벽하게 작동했습니다.

5

귀하의 JSON은 다음과 같이 될 것입니다 :

 { 
     "registration_ids": [ 
         "fcm token 1", 
         "fcm token 2", 
         "fcm token 3" 
        ], 
     "data": { 
       "message": "msg" 
       }, 
     "notification": { 
       "title": "App name", 
       "text": " your msg" 
      } 
    } 
public void sendGroupPush(Context context, ArrayList tokenlist, String message) { 
      String msg = message; 
      String title = context.getString(R.string.app_name); 
      JSONArray regId = null; 
      JSONObject objData = null; 
      JSONObject data = null; 
      JSONObject notif = null; 
      try { 
       regId = new JSONArray(); 
       for (int i = 0; i < tokenlist.size(); i++) { 
        regId.put(tokenlist.get(i)); 
       } 
       data = new JSONObject(); 
       data.put("message", message); 
       notif = new JSONObject(); 
       notif.put("title", title); 
       notif.put("text", msg); 

       objData = new JSONObject(); 
       objData.put("registration_ids", regId); 
       objData.put("data", data); 
       objData.put("notification", notif); 
       Log.e("[email protected]@_group_PASS:>", objData.toString()); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, Constants.FCM_PUSH_GROUP_URL, objData, 
        new Response.Listener<JSONObject>() { 
         @Override 
         public void onResponse(JSONObject response) { 
          Log.e("[email protected]@[email protected]@_SUCESS", response + ""); 
         } 
        }, 
        new Response.ErrorListener() { 
         @Override 
         public void onErrorResponse(VolleyError error) { 
          Log.e("[email protected]@[email protected]@_Errors--", error + ""); 
         } 
        }) { 
       @Override 
       public Map<String, String> getHeaders() throws AuthFailureError { 
        Map<String, String> params = new HashMap<String, String>(); 
        params.put("Authorization", "key=" + Constants.FCM_API_KEY); 
        params.put("Content-Type", "application/json"); 
        Log.e("[email protected]@[email protected]@PUSH_headrers", "::> " + params); 
        return params; 
       } 
      }; 
      RequestQueue requestQueue = Volley.newRequestQueue(context); 
      int socketTimeout = 1000 * 60;// 60 seconds 
      RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); 
      jsObjRequest.setRetryPolicy(policy); 
      requestQueue.add(jsObjRequest); 
     } 

공공 정적 문자열 FCM_PUSH_URL = "https://fcm.googleapis.com/fcm/send"; 코드 아래

7

을 사용하면 여러 장치에 푸시 알림을 보내 :

import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 
import com.google.android.gcm.server.Message; 
import com.google.android.gcm.server.MulticastResult; 
import com.google.android.gcm.server.Result; 
import com.google.android.gcm.server.Sender; 

public class PushNotifactionHelper { 
public final static String AUTH_KEY_FCM = "your key "; 
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send"; 

public static void sendPushNotification(List<String> deviceTokenList) { 
    Sender sender = new Sender(AUTH_KEY_FCM); 
    Message msg = new Message.Builder().addData("message", "Message body") 
      .build(); 
    try { 
     MulticastResult result = sender.send(msg, deviceTokenList, 5); 
     for (Result r : result.getResults()) { 
      if (r.getMessageId() != null) 
       System.out.println("Push Notification Sent Successfully"); 
      else 
       System.out.println("ErrorCode " + r.getErrorCodeName()); 
     } 
    } catch (IOException e) { 
     System.out.println("Error " + e.getLocalizedMessage()); 
    } 
    } 
    } 

참고 : 나뿐만 아니라 개인 푸시 메시지 그룹을 보내기위한 매우 간단한 해결책이

다음
+2

Works, charm Thanks. –

+1

코드에서 사용하지 않는 API_URL_FCM ..its가 사용됩니다. – kunal

+0

오류가있는 쓸모없는 코드, 감사합니다. :) – Alpha2k

2

사용 gcm.server.jar

public class FCM { 
final static private String FCM_URL = "https://fcm.googleapis.com/fcm/send"; 

/** 
* 
* Method to send push notification to Android FireBased Cloud messaging 
Server. 
* @param tokenId Generated and provided from Android Client Developer 
* @param server_key Key which is Generated in FCM Server 
    @param message which contains actual information. 
* 
*/ 

static void send_FCM_Notification(String tokenId, String server_key, String 

message){ 


    try{ 
// Create URL instance. 
URL url = new URL(FCM_URL); 
// create connection. 
HttpURLConnection conn; 
conn = (HttpURLConnection) url.openConnection(); 
conn.setUseCaches(false); 
conn.setDoInput(true); 
conn.setDoOutput(true); 
//set method as POST or GET 
conn.setRequestMethod("POST"); 
//pass FCM server key 
conn.setRequestProperty("Authorization","key="+server_key); 
//Specify Message Format 
conn.setRequestProperty("Content-Type","application/json"); 
//Create JSON Object & pass value 
JSONObject infoJson = new JSONObject(); 

infoJson.put("title","Alankit"); 
infoJson.put("body", message); 

JSONObject json = new JSONObject(); 
json.put("to",tokenId.trim()); 
json.put("notification", infoJson); 

System.out.println("json :" +json.toString()); 
System.out.println("infoJson :" +infoJson.toString()); 
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
wr.write(json.toString()); 
wr.flush(); 
int status = 0; 
if(null != conn){ 
status = conn.getResponseCode(); 
} 
if(status != 0){ 

if(status == 200){ 
//SUCCESS message 
BufferedReader reader = new BufferedReader(new 
InputStreamReader(conn.getInputStream())); 
System.out.println("Android Notification Response : " + reader.readLine()); 
}else if(status == 401){ 
//client side error 
System.out.println("Notification Response : TokenId : " + tokenId + " Error occurred :"); 
}else if(status == 501){ 
//server side error 
System.out.println("Notification Response : [ errorCode=ServerError ] TokenId : " + tokenId); 
}else if(status == 503){ 
//server side error 
System.out.println("Notification Response : FCM Service is Unavailable 
TokenId : " + tokenId); 
} 
} 
}catch(MalformedURLException mlfexception){ 
// Prototcal Error 
System.out.println("Error occurred while sending push Notification!.." + mlfexception.getMessage()); 
}catch(Exception mlfexception){ 
//URL problem 
System.out.println("Reading URL, Error occurred while sending push 
Notification!.." + mlfexception.getMessage()); 
} 

} 

static void send_FCM_NotificationMulti(List<String> putIds2, String 
tokenId, 
String server_key, String message){ 
    try{ 
    // Create URL instance. 
    URL url = new URL(FCM_URL); 
    // create connection. 
    HttpURLConnection conn; 
    conn = (HttpURLConnection) url.openConnection(); 
    conn.setUseCaches(false); 
    conn.setDoInput(true); 
    conn.setDoOutput(true); 
    //set method as POST or GET 
    conn.setRequestMethod("POST"); 
    //pass FCM server key 
    conn.setRequestProperty("Authorization","key="+server_key); 
    //Specify Message Format 
    conn.setRequestProperty("Content-Type","application/json"); 
    //Create JSON Object & pass value 

     JSONArray regId = null; 
     JSONObject objData = null; 
     JSONObject data = null; 
     JSONObject notif = null; 

      regId = new JSONArray(); 
      for (int i = 0; i < putIds2.size(); i++) { 
       regId.put(putIds2.get(i)); 
      } 
      data = new JSONObject(); 
      data.put("message", message); 
      notif = new JSONObject(); 
      notif.put("title", "Alankit Universe"); 
      notif.put("text", message); 

      objData = new JSONObject(); 
      objData.put("registration_ids", regId); 
      objData.put("data", data); 
      objData.put("notification", notif); 
      System.out.println("[email protected]@_group_PASS:>"+ objData.toString()); 


    System.out.println("json :" +objData.toString()); 
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 

    wr.write(objData.toString()); 
    wr.flush(); 
    int status = 0; 
    if(null != conn){ 
    status = conn.getResponseCode(); 
    } 
    if(status != 0){ 

     if(status == 200){ 
    //SUCCESS message 
    BufferedReader reader = new BufferedReader(new 
    InputStreamReader(conn.getInputStream())); 
    System.out.println("Android Notification Response : " + 
    reader.readLine()); 
    }else if(status == 401){ 
    //client side error 
    System.out.println("Notification Response : TokenId : " + tokenId + " 
     Error occurred :"); 
    }else if(status == 501){ 
    //server side error 
    System.out.println("Notification Response : [ errorCode=ServerError ] 
    TokenId : " + tokenId); 
    }else if(status == 503){ 
    //server side error 
    System.out.println("Notification Response : FCM Service is Unavailable 
    TokenId : " + tokenId); 
    } 
    } 
    }catch(MalformedURLException mlfexception){ 
    // Prototcal Error 
    System.out.println("Error occurred while sending push Notification!.." + 
    mlfexception.getMessage()); 
    }catch(IOException mlfexception){ 
    //URL problem 
    System.out.println("Reading URL, Error occurred while sending push 
    Notification!.." + mlfexception.getMessage()); 
    }catch (Exception exception) { 
    //General Error or exception. 
    System.out.println("Error occurred while sending push Notification!.." + 
exception.getMessage()); 
    } 

    } 

}

 Calling should be like that : 



    public class TestFCM { 
     static List<String> putIds; 
     public static void main(String[] args) { 

    //Just I am passed dummy information 
    // DeviceID's 

    String tokenId1 = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; 
    String tokenId = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"; 
    String server_key ="<Server Key>" ; 
    String message = "Welcome alankit Push Service."; 

    putIds= new ArrayList<>(); 
    putIds.add(tokenId1); 
    putIds.add(tokenId); 

    /* for Group*/ 
    FCM.send_FCM_NotificationMulti(putIds,tokenId,server_key,message); 

    /*for indevidual*/ 
    FCM.send_FCM_Notification(tokenId,server_key,message); 
    } 


} 
-1

인증 목적으로 Firebase Server Key 만 있으면됩니다. http 클라이언트 코드를 작성하기 만하면 모든 프로그래밍 언어를 사용할 수 있습니다.

체크 아웃 Github Repo. 자바 서버에서 firebase 푸시 알림을 보내기위한 완전한 Java Rest Client 프로젝트가 있습니다.

+0

이 링크는 질문에 대한 답변 일지 모르지만 여기에 답변의 핵심 부분을 포함시키고 참고.링크 된 페이지가 변경되면 링크 전용 답변이 유효하지 않게 될 수 있습니다. - [검토 중] (검토 중/리뷰/저품목 게시물/18463472) –

+0

okay sure bro :) –

관련 문제