【问题标题】:How to send FCM Token ID to PHP server?如何将 FCM 令牌 ID 发送到 PHP 服务器?
【发布时间】:2020-02-04 09:55:57
【问题描述】:

已生成 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);

?>

【问题讨论】:

    标签: java android firebase firebase-cloud-messaging


    【解决方案1】:

    您可以将 FCM-Id 存储在 Preference 中,然后将此 FCM-Id 传递给后端,使用 API 调用将其作为参数传递。在下面我得到 FCM-Id 并使用 API 传递给 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 通过,因为这是我的要求。

    在应用级 gradle 文件中添加调用 Volley API 调用的依赖项:

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

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

    Volley 库示例: Tutorial 1 Tutorial 2 Tutorial 3

    【讨论】:

    • 我在 localhost 上运行了一个 php 文件。当我在模拟器上运行应用程序时,它会生成令牌 ID。并将令牌发送给 PHP,
    • 所以在这里你可以为 API 调用创建本地函数并将这个 URL 放在上面的代码 sn-p: FCM_TOKEN_URL 在这里替换你的本地 URL。
    • 我为上面你写的代码导入了哪些库?
    • 检查我更新的答案导入:从 volley 库调用 API 的实现 'com.android.volley:volley:1.1.0'
    • 如果出现任何问题,请让男士知道。
    猜你喜欢
    • 2022-01-21
    • 2016-11-15
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 2011-11-20
    • 2021-08-01
    相关资源
    最近更新 更多