2012-07-21 26 views
31

Theo phần cuối cùng trong hướng dẫn GCM: Getting Started, có một số cuốn sách cần được thực hiện sau khi nhận được kết quả.GCM: MulticastResult - kết quả nào từ thiết bị nào?

Trích dẫn từ hướng dẫn:

Nó bây giờ cần thiết để phân tích kết quả và có những hành động thích hợp trong các trường hợp sau:

  • Nếu thông báo đã được tạo ra nhưng kết quả trả về đăng ký kinh điển ID, cần phải thay thế đăng ký hiện tại
    ID bằng ID chuẩn.
  • Nếu lỗi trả về không được đăng ký, bạn cần xóa ID đăng ký đó vì ứng dụng đã được gỡ cài đặt từ thiết bị.

Dưới đây là một đoạn mã để xử lý những 2 điều kiện:

if (result.getMessageId() != null) { 
String canonicalRegId = result.getCanonicalRegistrationId(); 
if (canonicalRegId != null) { 
    // same device has more than on registration ID: update database 
} 
} else { 
String error = result.getErrorCodeName(); 
if (error.equals(Constants.ERROR_NOT_REGISTERED)) { 
    // application has been removed from device - unregister database 
} 
} 

Hướng dẫn ở trên đề cập đến một đơn kết quả, chứ không phải trường hợp multicast. Tôi không chắc chắn cách xử lý trường hợp đa hướng:

ArrayList<String> devices = new ArrayList<String>(); 

    for (String d : relevantDevices) { 
     devices.add(d); 
    } 

    Sender sender = new Sender(myApiKey); 
    Message message = new Message.Builder().addData("hello", "world").build(); 
    try { 
     MulticastResult result = sender.send(message, devices, 5); 

     for (Result r : result.getResults()) { 
      if (r.getMessageId() != null) { 
       String canonicalRegId = r.getCanonicalRegistrationId(); 
       if (canonicalRegId != null) { 
        // same device has more than on registration ID: update database 
        // BUT WHICH DEVICE IS IT? 
       } 
      } else { 
       String error = r.getErrorCodeName(); 
       if (error.equals(Constants.ERROR_NOT_REGISTERED)) { 
        // application has been removed from device - unregister database 
        // BUT WHICH DEVICE IS IT? 
       } 
      } 
     } 
    } catch (IOException ex) { 
     Log.err(TAG, "sending message failed", ex); 
    } 

Tôi gửi danh sách thiết bị và nhận lại danh sách kết quả. Đối tượng kết quả không chứa id đăng ký, nhưng chỉ là id chuẩn nếu lần đầu tiên đã lỗi thời. Nó không có giấy tờ nếu hai danh sách có liên quan đến nhau (ví dụ: giữ gìn trật tự và kích cỡ).

Làm cách nào để đảm bảo kết quả nào đề cập đến thiết bị nào?

- CẬP NHẬT

tôi đã dán một đoạn của giải pháp trong một câu trả lời riêng biệt dưới đây

Trả lời

21

Kết quả là theo thứ tự của mảng registration_id của bạn mà bạn gửi đến máy chủ GCM. ví dụ. nếu registration_ids của bạn là:

[id1, id4, id7, id8] 

Sau đó mảng kết quả bạn nhận được sẽ có cùng thứ tự id1, id4, id7 và id8.

Bạn chỉ cần phân tích từng kết quả tương ứng, ví dụ: nếu kết quả thứ 2 có 'message_id' và 'registration_id' của 'id9', bạn biết 'id4' hiện đã lỗi thời và nên được thay thế bằng id9.

+0

cảm ơn! Tôi vừa tìm thấy thông tin này trong nhóm Google GCM (https://groups.google.com/forum/#!topic/android-gcm/DCHHQwqTs8M). Cần có thời gian để API mới có được tài liệu phù hợp .. – auval

+0

cảm ơn! đã tự hỏi mình cùng một câu hỏi! –

5

Đối với các độc giả tiện nghi, đây là một đoạn xử lý đáp ứng cho nhiều thiết bị

public void sendMessageToMultipleDevices(String key, String value, ArrayList<String> devices) { 

     Sender sender = new Sender(myApiKey); 
     Message message = new Message.Builder().addData(key, value).build(); 
     try { 
      MulticastResult result = sender.send(message, devices, 5); 
      MTLog.info(TAG, "result " + result.toString()); 


      for (int i = 0; i < result.getTotal(); i++) { 
       Result r = result.getResults().get(i); 

       if (r.getMessageId() != null) { 
        String canonicalRegId = r.getCanonicalRegistrationId(); 
        if (canonicalRegId != null) { 
         // devices.get(i) has more than on registration ID: update database 

        } 
       } else { 
        String error = r.getErrorCodeName(); 
        if (error.equals(Constants.ERROR_NOT_REGISTERED)) { 
         // application has been removed from devices.get(i) - unregister database 
        } 
       } 
      } 
     } catch (IOException ex) { 
      MTLog.err(TAG, "sending message failed", ex); 
     } 
    } 
+0

những gì có trong các giá trị? – Noman

+0

Lớp Kết quả có 3 trường: messageId, canonicalRegistrationId và errorCode. Tất cả các trường hợp có liên quan đều được đề cập trong đoạn mã. canonicalRegistrationId là khóa gcm được cập nhật. – auval

+0

'devices.get (i) có nhiều hơn một ID đăng ký: cập nhật cơ sở dữ liệu' - bạn nên làm gì ở đây? Xóa devices.get (i) khỏi cơ sở dữ liệu hoặc xóa thiết bị bằng canonicalRegistrationId khỏi kết quả? Hoặc kiểm tra xem thiết bị có canonicalRegistrationId có tồn tại trong cơ sở dữ liệu không? Nếu có, sau đó xóa một trong những khác, nếu sai, thay đổi id của một trong những khác? – Konsumierer

3

Giải pháp này được thực hiện bằng mẫu phát triển google GCM Demo application lưu ý các asyncSend cho multicasting xử lý

List<GcmUsers> devices=SearchRegisterdDevicesByCourseCommand.execute(instructorId, courseId); 
    String status; 
    if (devices.equals(Collections.<GcmUsers>emptyList())) {  
     status = "Message ignored as there is no device registered!"; 
    } else { 
     // NOTE: check below is for demonstration purposes; a real application 
     // could always send a multicast, even for just one recipient 
     if (devices.size() == 1) { 
     // send a single message using plain post 
     GcmUsers gcmUsers = devices.get(0); 
     Message message = new Message.Builder().build(); 
     Result result = sender.send(message, gcmUsers.getGcmRegid(), 5); 
     status = "Sent message to one device: " + result; 
     } else { 
     // send a multicast message using JSON 
     // must split in chunks of 1000 devices (GCM limit) 
     int total = devices.size(); 
     List<String> partialDevices = new ArrayList<String>(total); 
     int counter = 0; 
     int tasks = 0; 
     for (GcmUsers device : devices) { 
      counter++; 
      partialDevices.add(device.getGcmRegid()); 
      int partialSize = partialDevices.size(); 
      if (partialSize == MULTICAST_SIZE || counter == total) { 
      asyncSend(partialDevices); 
      partialDevices.clear(); 
      tasks++; 
      } 
     } 
     status = "Asynchronously sending " + tasks + " multicast messages to " + 
      total + " devices"; 
     } 
    } 
    req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString()); 






private void asyncSend(List<String> partialDevices) { 
    // make a copy 
    final List<String> devices = new ArrayList<String>(partialDevices); 
    threadPool.execute(new Runnable() { 

     public void run() { 
     Message message = new Message.Builder().build(); 
     MulticastResult multicastResult; 
     try { 
      multicastResult = sender.send(message, devices, 5); 
     } catch (IOException e) { 
      logger.log(Level.SEVERE, "Error posting messages", e); 
      return; 
     } 
     List<Result> results = multicastResult.getResults(); 
     // analyze the results 
     for (int i = 0; i < devices.size(); i++) { 
      String regId = devices.get(i); 
      Result result = results.get(i); 
      String messageId = result.getMessageId(); 
      if (messageId != null) { 
      logger.fine("Succesfully sent message to device: " + regId + 
       "; messageId = " + messageId); 
      String canonicalRegId = result.getCanonicalRegistrationId(); 
      if (canonicalRegId != null) { 
       // same device has more than on registration id: update it 
       logger.info("canonicalRegId " + canonicalRegId); 
       Datastore.updateRegistration(regId, canonicalRegId); 
      } 
      } else { 
      String error = result.getErrorCodeName(); 
      if (error.equals(Constants.ERROR_NOT_REGISTERED)) { 
       // application has been removed from device - unregister it 
       logger.info("Unregistered device: " + regId); 
       Datastore.unregister(regId); 
      } else { 
       logger.severe("Error sending message to " + regId + ": " + error); 
      } 
      } 
     } 
     }}); 
    } 
+0

có ghi chú trong ứng dụng mẫu mà bạn liên kết tới: "Thông tin trong tài liệu này đã bị thay thế bởi Máy chủ GCM và Ứng dụng khách GCM. Vui lòng sử dụng API GoogleCloudMessaging thay vì thư viện trình trợ giúp máy khách GCM. Thư viện trợ giúp máy chủ GCM vẫn hợp lệ. ". Câu trả lời của bạn có được cập nhật không? – auval

+0

cập nhật 2 tuần của nó trông google đã cập nhật thư viện và bản demo chưa được cập nhật :) – shareef

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