Android FCM通过触发服务显示通知

时间:2017-12-02 20:32:07

标签: android firebase google-cloud-messaging firebase-cloud-messaging

我尝试在我的应用中实施FCM,但我遇到了问题。每当我发送通知时,它都会显示默认通知,而不是调用我的自定义代码。我做错了什么?

这些是服务

<service
    android:name="com.backgroundws.MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>
<service
    android:name="com.backgroundws.MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>

这是我的 Java 代码:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d("MyFirebaseMessaging", "GotMessage");
        WSListener.sendEvent(this, "Push");
    }

}

当我在设备上收到通知时,我在logcat中看到了这一点:

I/SendBroadcastPermission: action:com.google.android.gms.gcm.ACTION_SCHEDULE, mPermissionType:0
I/SendBroadcastPermission: action:com.google.android.gms.gcm.ACTION_SCHEDULE, mPermissionType:0

这是我发送通知的方式:

function send_gcm_notify($reg_id, $message, $url, $key) {
        $fields = array(

            'to'                   => $reg_id ,
            'priority'             => "high",
            "notification"         => array("body"=>$message),
            'data'                 => array( "url"=> $url)
        );

        $headers = array(
            'Content-Type: application/json',
            'Authorization: key=' . $key
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        $result = curl_exec($ch);
        if ($result === FALSE) {
            //die('Problem occurred: ' . curl_error($ch));
        }
        curl_close($ch);
        return $result;

    }

当然我测试了,服务的路径是正确的。

1 个答案:

答案 0 :(得分:2)

如果您希望服务器的内容在两种模式(背景和前景)中都有通知,则必须从服务器内部发送有效负载&#39;数据&#39;只要。 有关详情,请参阅此处How to handle Android FCM Messages when application is in Background with data payload?