如何将 FCM 令牌 ID 发送到 PHP 服务器?

How to send FCM Token ID to PHP server?

已生成 FCM 令牌 ID,我希望将其发送到 PHP 服务器,然后将其存储在变量中。应该采取什么方法?

    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        sendRegistrationToServer(token);
    }

    private void sendRegistrationToServer(String token) {
    }

PHP代码

<?php

$token = $_POST["tokenid"];
echo ($token);

?>

您可以将 FCM-Id 存储在首选项中,然后使用 API 调用将此 FCM-Id 作为参数传递给后端。在下面,我使用 API.

获取 FCM-Id 并传递给 PHP

MyFirebaseInstanceIDService.java

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";
    Context context;

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);
        context = getApplicationContext();

        AppPreference.setStringPref(context, AppPreference.PREF_SIGNUP_FCM_ID, AppPreference.PREF_KEY.PREF_KEY_FCM_ID,
                refreshedToken);
        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        sendRegistrationToServer(refreshedToken);
    }

    // [END refresh_token]


    /**
     * Persist token to third-party servers.
     * <p>
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.


        Map<String, String> params = new HashMap<String, String>();
        String device_id = Common.getDeviceId(this);
        params.put(FCM_TOKEN, token);
        params.put(DEVICEID, device_id);
        params.put(DEVICE_TYPE, device_type);
        JsonObjectRequest request = new JsonObjectRequest(FCM_TOKEN_URL, new JSONObject(params),
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            parseJsonPersonalDetail(response);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (error.networkResponse != null) {
                            int statusCode = error.networkResponse.statusCode;
                            NetworkResponse response = error.networkResponse;

                            Log.d("testerror", "" + statusCode + " " + response.data);
                        }
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("User-agent", "Mozilla/5.0 (TV; rv:44.0) Gecko/44.0 Firefox/44.0");
                return headers;
            }
        };

        Common.setVolleyConnectionTimeout(request);
        ApplicationClass.getInstance().getRequestQueue().add(request);

    }


    /**
     * <b>Description</b> - Get back response for calling  callUserDetailSave API
     *
     * @param jsonObject - Pass API response
     */
    private void parseJsonPersonalDetail(JSONObject jsonObject) {
        try {
            Log.i("get response", "get response" + jsonObject);
            if (jsonObject.toString().contains(Constant.JSON_KEY.MSG)) {
                String message = jsonObject.getString(Constant.JSON_KEY.MSG);
                String status = jsonObject.getString(Constant.JSON_KEY.CODE);
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }
}

这里我首先获取 FCM id 然后调用 API 方法 sendRegistrationToServer 并在 API 中传递令牌作为参数以便后端开发人员从 API 参数.

这里我传递三个参数

  • params.put(FCM_TOKEN, 令牌);
  • params.put(DEVICEID, device_id);
  • params.put(DEVICE_TYPE, device_type);

device_iddevice_type 通过,因为这是我的要求。

Add dependency in app level gradle file for calling Volley API call :

implementation 'com.android.volley:volley:1.1.0'

结帐我为您创建了演示:Demo

Volley 库示例: Tutorial 1 Tutorial 2 Tutorial 3