2016-06-01 28 views
12

Tôi đang cố gửi thông báo Đẩy tới thiết bị Android của mình bằng dịch vụ Firebase mới. Tôi đã đăng ký và thiết lập một ứng dụng, tôi cũng đặt tất cả mã cần thiết để nhận thông báo trong ứng dụng android. Qua Bảng điều khiển Firebase, tôi có thể gửi thông báo đến ứng dụng của tôi và nó được nhận và hiển thị. Bây giờ tôi muốn viết một máy chủ độc lập java, để gửi một thông báo tới TẤT CẢ các thiết bị. Đây là mã hiện tại của tôi:Máy chủ Java Firebase để gửi thông báo đẩy tới tất cả các thiết bị

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()); 

Và đây là kết quả mà tôi nhận lại từ các máy chủ của họ:

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

Thật không may, chỉ cần loại bỏ các "thành" thẻ không hoạt động, tôi nhận được một mã 400 trở lại sau đó. Tôi đọc rằng tôi cần phải đăng ký thiết bị, gửi id thiết bị đến máy chủ và lưu nó vào đó rồi vòng qua tất cả các thiết bị đã đăng ký trên máy chủ để gửi tin nhắn. Không có cách nào dễ dàng hơn, chỉ cần gửi tin nhắn đến tất cả các thiết bị, giống như trong bảng điều khiển?

sự giúp đỡ của bạn là thực sự đánh giá cao, vì tôi đã cố gắng để có được điều này để làm việc tất cả các ngày dài = (

Kính trọng, Dustin

Trả lời

11

Tôi không tin rằng điều này là có thể. Thay vào đó, những gì tôi xin đề nghị được đăng ký tất cả các thiết bị với cùng một chủ đề và sau đó bạn có thể nhắn tin tất cả các thiết bị cùng một lúc đây là tài liệu giúp đỡ về vấn đề này:.

Gửi tin nhắn Topic từ server

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

+0

Vâng tôi cũng nghĩ về cách làm theo cách này, nhưng tôi không muốn làm bất kỳ mã đăng ký nào trong ứng dụng ... Bất kỳ ý tưởng nào nếu điều đó có thể bằng cách nào đó? – user3907491

+3

Bạn có ý nghĩa gì với mã đăng ký trong ứng dụng? Khi người dùng của bạn khởi động ứng dụng, bạn có thể tự động đăng ký chúng với chủ đề. Trong Android, nó sẽ trông như thế này: 'FirebaseMessaging.getInstance(). SubscribeToTopic (" allDevices ");' Bạn sẽ đặt điều này trong phương thức onCreate và khi ứng dụng bắt đầu, chúng sẽ tự động được đăng ký. –

+0

Tuyệt vời, cảm ơn sự giúp đỡ của bạn! Đó chính là điều tôi đang tìm kiếm =) Làm cách nào để gắn thẻ câu trả lời của bạn là câu trả lời hay nhất? Đã +1 nó – user3907491

1

client Android mã phía nên:

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

Server side:

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

Giải pháp này gửi thông báo Push to căn cứ hỏa lực sử dụng Apache HttpClient:

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

Tôi gặp một lỗi với mã của bạn: 'HttpClientBuilder không thể được giải quyết'. Làm thế nào để sửa lỗi đó? – Peter

+0

Bạn đã thêm phụ thuộc maven chưa? org.apache.httpcomponents httpclient \t 4.5.2 Geucimar

+0

gì chính xác là ' "để"' giá trị trong '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); 
} 

bạn có thể nhận các lớp học tại đây: https://github.com/AndreiD/testingpushnotifications

+0

Tôi đã kiểm tra mã của bạn nhưng những gì tôi không hiểu là tại sao bạn đang sử dụng '' 'HeaderRequestInterceptor''' trong khi bạn chỉ có thể sử dụng' '' HttpHeaders''' để thiết lập tiêu đề và đặt vào '' 'HttpEntity''' – zt1983811

3

mã của bạn hoàn hảo chỉ cần kiểm tra lại id đăng ký của người dùng mà bạn đang gửi thông báo. Thay cho to, hãy sử dụng thiết bị người dùng regid. Nó làm việc hoàn hảo cho tôi.

5

JSON của bạn sẽ như thế này:

 { 
     "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); 
     } 

public static String FCM_PUSH_URL = "https://fcm.googleapis.com/fcm/send";

7

Sử dụng mã dưới đây để gửi thông báo đẩy cho nhiều thiết bị:

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()); 
    } 
    } 
    } 

Lưu ý: sử dụng gcm.server.jar

+2

Works, như charm Thanks. –

+1

việc sử dụng API_URL_FCM ..its không được sử dụng trong mã – kunal

+0

Mã vô dụng có lỗi, cảm ơn :) – Alpha2k

2

Ở đây tôi có giải pháp rất đơn giản cho việc gửi nhóm nhắn push cũng cá nhân

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

Tất cả những gì bạn cần là Khóa máy chủ Firebase cho mục đích ủy quyền. Bạn chỉ cần viết mã máy khách http, bạn có thể sử dụng bất kỳ ngôn ngữ lập trình nào cho mục đích đó.

Kiểm tra điều này Github Repo. Nó có dự án Java Rest Client hoàn chỉnh để gửi thông báo đẩy firebase từ máy chủ java.

+0

Trong khi liên kết này có thể trả lời câu hỏi, tốt hơn nên bao gồm các phần quan trọng của câu trả lời ở đây và cung cấp liên kết cho tài liệu tham khảo.Câu trả lời chỉ liên kết có thể trở thành không hợp lệ nếu trang được liên kết thay đổi. - [Từ đánh giá] (/ đánh giá/chất lượng thấp-bài viết/18463472) –

+0

okay chắc chắn bro :) –

Các vấn đề liên quan