0

我想在不使用Firebase控制檯(我想與服務器端進行)的情況下發送通知。爲此,我試圖將設備令牌標識發送到Web服務。我在此Android項目中使用Firebase雲消息傳遞。我怎樣才能做到這一點?發送令牌ID到服務器端Android

public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService{ 

    private static final String TAG = "MyFirebaseIIDService"; 

    @Override 
    public void onTokenRefresh() { 
     String token = FirebaseInstanceId.getInstance().getToken(); 
     Log.d(TAG, "Token: " + token); 

     sendRegistrationToServer(token); 
    } 

    private void sendRegistrationToServer(String token) { 
     // send token to web service ?? 

    } 

謝謝!

+0

是否要將您的令牌ID存儲在Firebase服務器上或您自己的? – Hamza

+0

@AmeerHamza我想在Firebase服務器上存儲 –

+0

下面的答案有幫助嗎?或者,您仍然有問題需要存儲到Firebase服務器中。 –

回答

0

我找到了我的問題從stackoverflow的答案。我希望這也能爲你工作。此代碼將消息和令牌ID發送到服務器。

public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService { 

private static final String TAG = "MyFirebaseIIDService"; 
public final static String AUTH_KEY_FCM = "your key here"; 
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send"; 

public void onTokenRefresh() { 
    String token = FirebaseInstanceId.getInstance().getToken(); 
    Log.d(TAG, "Token: " + token); 

} 
public void sendAndroidNotification(String deviceToken, String message, String title) throws IOException { 

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 

    StrictMode.setThreadPolicy(policy); 


    OkHttpClient client = new OkHttpClient(); 
    MediaType mediaType = MediaType.parse("application/json"); 
    JSONObject obj = new JSONObject(); 
    JSONObject msgObject = new JSONObject(); 
    try { 
     msgObject.put("body", message); 
     Log.d("Body",message); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    try { 
     msgObject.put("title", title); 
     Log.d("Title",title); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    try { 
     msgObject.put("icon", R.mipmap.ic_launcher); 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    // msgObject.put("color",); 

    try { 
     obj.put("to", deviceToken); 
     Log.d("to",deviceToken); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    try { 
     obj.put("notification",msgObject); 
     Log.d("Body",msgObject.toString()); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

    RequestBody body = RequestBody.create(mediaType, obj.toString()); 
    Request request = new Request.Builder().url(API_URL_FCM).post(body) 
      .addHeader("content-type", CONTENT_TYPE) 
      .addHeader("authorization", "key="+AUTH_KEY_FCM).build(); 
    Log.d("Request",body.toString()); 
    Response response = client.newCall(request).execute(); 
    Log.d("Notification response",response.body().string()); 

     } 
} 
1

首先,您應該運行一些服務器來接收令牌和存儲。然後,您可以從您的應用程序進行API調用,以將FCM令牌發佈到您的服務器。

2

1)穿心蓮像這樣的

private void sendRegistrationToServer(String token) { 
      // send token to web service ?? 
     final FirebaseDatabase database = FirebaseDatabase.getInstance(); 
     DatabaseReference ref = database.getReference("server/saving-data/IDs"); 
     // then store your token ID 
     ref.push().setvalue(token) 
    } 

對於火力REF多個讀this post

0

粘貼在類下面給出該代碼和該方法將從「onTokenRefresh()」方法自動exected。只要確保使用您自己的服務器的Web服務URL替換Web服務URL。

private void sendRegistrationToServer(String deviceToken) { 

class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { 

    @Override 
    protected String doInBackground(String... params) { 
     String deviceToken = params[0]; 



     HttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(
      "http://lib-dm.process9.com/libertydm/ValidateUserHandler.ashx");// replace with your url 
     httpPost.addHeader("Content-type", 
      "application/x-www-form-urlencoded"); 
     BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair(
      "UserId", paramUsername); // Make your own key value pair 
     BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair(
      "Password", paramPassword);// make your own key value pair 

     // You can add more parameters like above 

     List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); 
     nameValuePairList.add(usernameBasicNameValuePair); 
     nameValuePairList.add(passwordBasicNameValuePair); 

     try { 
      UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
       nameValuePairList); 
      httpPost.setEntity(urlEncodedFormEntity); 

      try { 
       HttpResponse httpResponse = httpClient 
        .execute(httpPost); 
       InputStream inputStream = httpResponse.getEntity() 
        .getContent(); 
       InputStreamReader inputStreamReader = new InputStreamReader(
        inputStream); 
       BufferedReader bufferedReader = new BufferedReader(
        inputStreamReader); 
       StringBuilder stringBuilder = new StringBuilder(); 
       String bufferedStrChunk = null; 
       while ((bufferedStrChunk = bufferedReader.readLine()) != null) { 
        stringBuilder.append(bufferedStrChunk); 
       } 

       return stringBuilder.toString(); 

       } catch (ClientProtocolException cpe) { 
        System.out 
         .println("First Exception coz of HttpResponese :" 
          + cpe); 
        cpe.printStackTrace(); 
       } catch (IOException ioe) { 
        System.out 
         .println("Second Exception coz of HttpResponse :" 
          + ioe); 
        ioe.printStackTrace(); 
       } 

     } catch (UnsupportedEncodingException uee) { 
      System.out 
       .println("An Exception given because of UrlEncodedFormEntity argument :" 
        + uee); 
      uee.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 
    } 
} 

SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); 
sendPostReqAsyncTask.execute(token); 
}