重启设备并清除应用后,如何解决FCM通知或工作?

时间:2016-12-23 09:44:37

标签: android firebase firebase-cloud-messaging

我希望我的Android应用程序即使设备重新启动也能继续接收通知(FCM)。

现在,我的应用必须首先打开应用,以便显示通知。

如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

请参阅: https://firebase.google.com/docs/cloud-messaging/android/receive

您可以在服务器的消息中保留data有效负载而不是notification有效负载。无论您的应用程序位于前台还是后台,都会调用onMessageReceived

答案 1 :(得分:1)

MyFireBaseInstanceIDService课程中,从onTokenRefresh方法上传到您的服务器,即

public class MyFireBaseInstanceIDService extends FirebaseInstanceIdService {
    private SessionManager session;

    /**
     * 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.
        session = new SessionManager(getApplicationContext());
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Logger.e("FCM Refreshed token: " + refreshedToken);
        if (session.getDataByKey(SessionManager.IS_LOGIN, false)) {
            sendRegistrationToServer(refreshedToken);
        }
    }

    /**
     * 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) {
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", session.getUserId());
        params.put("device_id", token);
        params.put("device_type", "A");
        params.put("encrypted_data", Utils.encode(session.getUserId()));

        Retrofit.getInstance("user/updatedevice", params)
                .enqueue(new Retrofit() {
                    @Override
                    public void onResponse(int statusCode, JSONObject jResponse) {
                        Logger.e("Refresh Token updated to server.");
                    }

                    @Override
                    public void onFailed(int statusCode, String message) {
                        Logger.e("Failed to updated Refresh Token to server.");
                    }
                });

    }
}