当应用程序被杀死时,来自FCM的数据消息未启用onMessage

时间:2017-05-16 09:00:18

标签: android firebase push-notification firebase-cloud-messaging

根据https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages,我可以使用数据消息,这些消息将100%收到onMessageReceived方法并相应地采取行动。但在我的情况下,当应用程序被杀时,我的所有消息都没有收到。虽然我只在Nexus 5测试时收到它们。以下是我的数据有效负载。

05-16 06:46:01.663 13199-29574/jss.test E/MyFirebaseMsgService: Data Payload: {data={"image":null,"title":"My message"}}
05-16 06:46:01.667 13199-29574/jss.test E/Providerfalse: true
05-16 06:46:01.667 13199-29574/jss.test E/MyFirebaseMsgService: Notification JSON {"data":{"image":null,"title":"My message"}}

对于FCM的清单如下:

 <service
            android:name=".FirebaseMessagingService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

Firebasemessaging服务:

  @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        if (remoteMessage.getData().size() > 0) {

            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
                sendPushNotification(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }


    //this method will display the notification
    //We are passing the JSONObject that is received from
    //firebase cloud messaging
    private void sendPushNotification(JSONObject json) {
                   //optionally we can display the json into log
        Log.e(TAG, "Notification JSON " + json.toString());
        try {
            //getting the json data
            JSONObject data = json.getJSONObject("data");

            //parsing json data
            String title = data.getString("title");
            String message = data.getString("message");
            String imageUrl = data.getString("image");

//code to call service if message has specific data values.
    }
        catch (Exception e) {
                    e.printStackTrace();    }}

你能指导我修复的地方,让它完美运作。

5 个答案:

答案 0 :(得分:0)

根据我在fcm实现中的测试,如果我在数据和数据中传递数据通知密钥然后我能够在onMessageReceived方法中获得通知,只有运行其他方面的应用程序我无法获得通知,如果我只使用数据密钥发送通知,那么它在两个方案中都有效, 因此,如果您的通知数据中存在通知密钥,请将其删除并进行测试,这可能会有效。

答案 1 :(得分:0)

尝试以下方法帮助您

private void sendNotification(String text, String senderId, String receiverId) {
        HttpsURLConnection conHttp = null;
        try {

            URL url = new URL("https://fcm.googleapis.com/fcm/send");
            conHttp = (HttpsURLConnection) url.openConnection();
            conHttp.setDoOutput(true);
            conHttp.setDoInput(true);
            conHttp.setRequestMethod("POST");
            conHttp.setRequestProperty("Content-Type", "application/json");
            //Put below you FCM API Key instead
            conHttp.setRequestProperty("Authorization", "key="
                    + “YOUR_FCM_API_KEY”);

            JSONObject root = new JSONObject();
            JSONObject data = new JSONObject();
            data.put(KEY_FCM_TEXT, text);
            data.put(KEY_FCM_SENDER_ID, sender);
            root.put("data", data);
            root.put("to", "/topics/user_" + receiverId);

            byte[] outputBytes = root.toString().getBytes("UTF-8");
            OutputStream os = conHttp.getOutputStream();
            os.write(outputBytes);
            os.flush();
            os.close();
            conHttp.getInputStream(); //do not remove this line. request will not work without it gg

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (conHttp != null) conHttp.disconnect();
        }
    }

答案 2 :(得分:0)

在服务清单中再定义一件事:

android:stopWithTask="false"

它应该是可行的,否则没有方法可以在应用被杀死时从onMessageReceived获取消息。

答案 3 :(得分:0)

尝试使用getBody()而不是getData():

    @Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    if (remoteMessage.getBody().toString.length() > 0) {

        Log.e(TAG, "Data Payload: " + remoteMessage.getBody().toString());
        try {
            JSONObject json = new JSONObject(remoteMessage.getBody().toString());
            sendPushNotification(json);
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
}


//this method will display the notification
//We are passing the JSONObject that is received from
//firebase cloud messaging
private void sendPushNotification(JSONObject json) {
               //optionally we can display the json into log
    Log.e(TAG, "Notification JSON " + json.toString());
    try {
        //getting the json data
        JSONObject data = json.getJSONObject("data");

        //parsing json data
        String title = data.getString("title");
        String message = data.getString("message");
        String imageUrl = data.getString("image");

}
    catch (Exception e) {
                e.printStackTrace();    }}

答案 4 :(得分:0)

func login(cpf: String) -> Observable<Bool> {
    let url = URL(string: AccessibilityDataAccessProvider.kLoginURL)
    let params = ["username": String.init(describing: cpf)]

    return dataAccessProvider.postSimpleResponse(url: url!, params: params)
        .do(onNext: {
            let userData = UserDefaults.standard
            userData.set(userToken, forKey: AccessibilityDataAccessProvider.userTokenKey)
        })
        .map { _ in
            return true
    }
}