2017-01-03 50 views
0

我試圖使用Firebase雲消息傳遞向我的Android設備發送通知。顯然一切都很好。我得到的答案爲我的HTTP請求:未使用自定義服務器顯示Android Firebase通知

Response Code : 200 

{"message_id": **ID here** } 

但我安裝了APK模擬器並沒有接收到通知,即使是在應用上的前景。

當通過Firebase控制檯發送消息時,一切正常。

任何人都可以幫助我找出問題所在?

import java.io.BufferedReader; 
    import java.io.IOException; 
    import java.io.InputStreamReader; 
    import java.io.OutputStreamWriter; 
    import java.io.UnsupportedEncodingException; 
    import java.net.HttpURLConnection; 
    import java.net.URL; 
    import java.util.Base64; 


    public class Main { 

     public static void main(String[] args) throws UnsupportedEncodingException, IOException { 

      String apiKey = "AI...LoU"; //My key here 

      String out = "{\"notification\":{\"title\": \"My title\", \"text\": \"My text\"}, \"to\":\"/topics/all\",\"data\": {\"key\": \"value\"}}"; 

      URL url = new URL("https://fcm.googleapis.com/fcm/send"); 

      String credentials = "key=" + apiKey; 
      //String basicAuth = "Basic " + new String(Base64.getEncoder().encodeToString(credentials.getBytes())); 

      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setUseCaches(false); 
      conn.setDoInput(true); 
      conn.setDoOutput(true); 
      conn.setRequestMethod("POST"); 
      conn.setRequestProperty("Content-Type", "application/json"); 
      conn.setRequestProperty("Authorization", credentials); 

      conn.connect(); 

      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
      wr.write(out); 
      wr.flush(); 

      int responseCode = conn.getResponseCode(); 
      System.out.println("Response Code : " + responseCode); 

      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      String inputLine; 
      while ((inputLine = in.readLine()) != null) { 
       System.out.println(inputLine); 
      } 
      in.close(); 
      wr.close(); 
     } 

    } 
+0

這可能是模擬器中的網絡問題。發送通知後,在模擬器中打開飛行模式並關閉飛行模式,您將收到所有通知。 –

+0

我在使用Firebase控制檯時收到通知。我認爲網絡工作正常。我只是在使用這個http post請求時沒有收到通知。 – felipepo

+0

你是否肯定設備(模擬器)訂閱了「全部」主題? –

回答

0

確保設備訂閱了相應的主題。在這種情況下,您應在客戶端撥打subscribeToTopic()訂閱all

+1

只是補充!當我的應用程序創建時,在啓動器活動的onCreate方法中,我添加了以下行: FirebaseMessaging.getInstance()。subscribeToTopic(「all」); 現在它工作完美。 – felipepo