Java 从GCM迁移到FCM

Java 从GCM迁移到FCM,java,php,android,Java,Php,Android,最近我从GCM迁移到了FCM,在过去的几天里,我一直在努力让它工作 Android应用程序正在从google firebase控制台接收通知,但它们没有从php服务器接收通知 这是我的PHP服务器端代码: <?php define("GOOGLE_API_KEY", Setting::get('browser_key') ? Setting::get('browser_key') : ""); class GCM { function __construct() { }

最近我从GCM迁移到了FCM,在过去的几天里,我一直在努力让它工作

Android应用程序正在从google firebase控制台接收通知,但它们没有从php服务器接收通知

这是我的PHP服务器端代码:

<?php



define("GOOGLE_API_KEY", Setting::get('browser_key') ? Setting::get('browser_key') : "");


class GCM {

function __construct() {

}


public function send_notification($registatoin_ids, $message) {

    Log::info("GOOGLE_API_KEY".GOOGLE_API_KEY);

    include_once 'const.php';
    $url = 'https://fcm.googleapis.com/fcm/send';

    $fields = array(
        'registration_ids' => $registatoin_ids,
        'data' => $message,
    );

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

    Log::info('***** PUSH MESSAGE ******'.print_r(json_encode($fields),true));

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);

    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);

    Log::info(print_r($result,true));

    if ($result === FALSE) {
        //die('Curl failed: ' . curl_error($ch));
        Log::error('Curl failed: ' . curl_error($ch));
    }
    else{
        //echo $result;
        Log::error($result);
    }

    // Close connection
    /*curl_close($ch);
     echo $result/*."\n\n".json_encode($fields); */

}

}
?>
这就是我在logcat android studio中不断遇到的错误:

 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.messaging.RemoteMessage$Notification.getBody()' on a null object reference
    at hr.trazim.client.services.MessagingService.onMessageReceived(MessagingService.java:32)
    at com.google.firebase.messaging.FirebaseMessagingService.zzd(Unknown Source:60)
    at com.google.firebase.iid.zzg.run(Unknown Source:4)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at com.google.android.gms.common.util.concurrent.zza.run(Unknown Source:6)
    at java.lang.Thread.run(Thread.java:919)
2020-01-07 12:08:11.092 1732-29214/?E/ResolverController:没有有效的NAT64前缀(101,/0)

我读了很多关于stackoverflow这样的主题,但找不到合适的解决方案。我希望这个补丁能帮助像我这样的开发人员找到合适的答案,而不会像我一样浪费太多时间

另外,如果您需要我的令牌,我还没有迁移它,但它正在工作,代码如下:

public class InstanceIDService extends FirebaseInstanceIdService {

@Override
public void onTokenRefresh() {
    super.onTokenRefresh();
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.e("FCMToken", refreshedToken);
    saveDeviceToken(refreshedToken);
}

private void saveDeviceToken(String token) {
    UserDataSource.getDataInstance().putDeviceToken(token);
}

}

提前感谢。

您的数据有误。应该是这样的。或者尝试先打印数据,然后从数组中获取数据

sendNotification(remoteMessage.getData().get("message"));
Log.d("Push data", remoteMessage.getData().toString());
尝试使用以下方法:

@TargetApi(Build.VERSION_CODES.O)
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)

public void show_Notification(){

Intent intent=new Intent(getApplicationContext(),MainActivity.class);
String CHANNEL_ID="MYCHANNEL";
NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,"name",NotificationManager.IMPORTANCE_LOW);
PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(),1,intent,0);
Notification notification=new Notification.Builder(getApplicationContext(),CHANNEL_ID)
        .setContentText("Heading")
        .setContentTitle("subheading")
        .setContentIntent(pendingIntent)
        .addAction(android.R.drawable.sym_action_chat,"Title",pendingIntent)
        .setChannelId(CHANNEL_ID)
        .setSmallIcon(android.R.drawable.sym_action_chat)
        .build();

NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(1,notification);


 }
要从php服务器发送,可以使用以下代码

<?php

function sendMessage($data, $target, $serverKey){
    //FCM api URL
    $rsp = [];
    $url = 'https://fcm.googleapis.com/fcm/send';
    //api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
    $server_key = $serverKey;
    $fields = array();
    $fields['data'] = $data;
    if(is_array($target)){
            $fields['registration_ids'] = $target;
        }else{
            $fields['to'] = $target;
    }
    //header with content_type api key
    $headers = array(
        'Content-Type:application/json',
        'Authorization:key='.$server_key
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    if ($result === FALSE) {
        //die('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);

    //print_r($result);
    return $result;
}

检查此链接也参考此链接,我认为在android中你不需要更改。昨天我尝试了本文提供的所有解决方案,不幸的是,我找不到其中的修复方案。我知道你的第一个链接,我现在检查第二个。你在安卓系统中得到了错误,对吗?后端工作正常?后端发送数据,但android无法处理。说nullIve tryed,现在我得到了:致命异常:Firebase MessagingService进程:hr.trazim.client,PID:29556 java.lang.IllegalArgumentException:无效通知(没有有效的小图标):通知(频道=null pri=0内容视图=null振动=null声音=content://settings/system/notification_sound 默认值=0x0标志=0x10颜色=0x00000000 vis=专用)你能解释一下它与问题错误的关系吗?检查下面答案的注释Sim试图实现此解决方案是针对androidx的吗?如果api处于jelly状态,会发生什么情况,因为我设定了最低目标19。我可以从本博客获得全面集成的帮助:谢谢你,我修复了它。谢谢兄弟
@TargetApi(Build.VERSION_CODES.O)
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)

public void show_Notification(){

Intent intent=new Intent(getApplicationContext(),MainActivity.class);
String CHANNEL_ID="MYCHANNEL";
NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,"name",NotificationManager.IMPORTANCE_LOW);
PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(),1,intent,0);
Notification notification=new Notification.Builder(getApplicationContext(),CHANNEL_ID)
        .setContentText("Heading")
        .setContentTitle("subheading")
        .setContentIntent(pendingIntent)
        .addAction(android.R.drawable.sym_action_chat,"Title",pendingIntent)
        .setChannelId(CHANNEL_ID)
        .setSmallIcon(android.R.drawable.sym_action_chat)
        .build();

NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(1,notification);


 }
<?php

function sendMessage($data, $target, $serverKey){
    //FCM api URL
    $rsp = [];
    $url = 'https://fcm.googleapis.com/fcm/send';
    //api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
    $server_key = $serverKey;
    $fields = array();
    $fields['data'] = $data;
    if(is_array($target)){
            $fields['registration_ids'] = $target;
        }else{
            $fields['to'] = $target;
    }
    //header with content_type api key
    $headers = array(
        'Content-Type:application/json',
        'Authorization:key='.$server_key
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    if ($result === FALSE) {
        //die('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);

    //print_r($result);
    return $result;
}