Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/223.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Firebase无法接收来自php的通知_Php_Android_Firebase_Firebase Cloud Messaging - Fatal编程技术网

Firebase无法接收来自php的通知

Firebase无法接收来自php的通知,php,android,firebase,firebase-cloud-messaging,Php,Android,Firebase,Firebase Cloud Messaging,我可以成功地从Firebase控制台接收通知,但当我调用PHP函数来执行此操作时,没有收到任何通知。正如我在互联网上看到的,这是我发送这些通知的方式。我不明白的是,当我切换到Firebase控制台时会有什么不同(因为它在那里工作)。我不认为问题出在我的应用程序上,因为我向他们的服务器发送了一个请求,然后他们应该发送到我的设备上。犯错误是很有可能的,请不要太粗鲁。我还是个初学者。谢谢你明智的回答 PHP函数 function push_notification_android($device_id

我可以成功地从Firebase控制台接收通知,但当我调用PHP函数来执行此操作时,没有收到任何通知。正如我在互联网上看到的,这是我发送这些通知的方式。我不明白的是,当我切换到Firebase控制台时会有什么不同(因为它在那里工作)。我不认为问题出在我的应用程序上,因为我向他们的服务器发送了一个请求,然后他们应该发送到我的设备上。犯错误是很有可能的,请不要太粗鲁。我还是个初学者。谢谢你明智的回答

PHP函数

function push_notification_android($device_id,$message){

    //API URL of FCM
    $url = 'https://fcm.googleapis.com/fcm/send';


    $api_key = 'MY_KEY';
                
    $fields = array (
        'to' => $device_id,
        'data' => array(
                "message" => $message,
                "id" => '1',
        ),
    );

    //header includes Content type and api key
    $headers = array(
        'Content-Type:application/json',
        'Authorization: key='.$api_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_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);

    curl_close($ch);
    echo $result;
    return $result;
}
{“多播_-id”:7370520341381062896,“成功”:1,“失败”:0,“规范_-id”:0,“结果”:[{“消息_-id”:“0:1611404485967655%6B3455F6B3455F”}]


通过文档,您可以向客户端发送两种类型的消息:

通知消息-由FCM SDK自动处理

数据消息-由客户端应用程序处理

如果您想发送数据消息,请像这样实现FirebaseMessagingService(这只是一个示例,您可以使用它,但可以根据需要进行改进,还可以测试所有可能的解决方案以了解其工作原理)

公共类MyFirebaseMessagingService扩展了FirebaseMessagingService{
@凌驾
收到消息时公共无效(RemoteMessage RemoteMessage){
如果(remoteMessage.getData().size()>0){
handleDataMessage(remoteMessage.getData());
}else if(remoteMessage.getNotification()!=null){
//如果您不需要或不需要改进,请删除此行。。。
sendNotification(100,remoteMessage.getNotification().getBody());
}
}
私有void handleDataMessage(地图数据){
if(data.containsKey(“id”)和&data.containsKey(“消息”)){
字符串消息=data.get(“消息”);
int-id;
试一试{
id=Integer.parseInt(data.get(“id”));
}捕获(例外e){
e、 printStackTrace();
id=1;//服务器错误id的默认id或其他内容
}
发送通知(id、消息);
}
}
私有void sendNotification(int-id,字符串messageBody){
意向意向=新意向(此,MainActivity.class);
intent.addFlags(intent.FLAG\u ACTIVITY\u CLEAR\u TOP);
PendingEvent PendingEvent=PendingEvent.getActivity(this,0,intent,PendingEvent.FLAG_ONE_SHOT);
String channelId=“appChannelId”;//getString(R.String.default\u notification\u channel\u id);
Uri defaultSoundUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_通知);
NotificationCompat.Builder notificationBuilder=
新建NotificationCompat.Builder(此,channelId)
.setSmallIcon(R.drawable.icon)//设置图标
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.iconpro_round))//设置图标
.setContentTitle(“MyApp”)
.setContentText(messageBody)
.setAutoCancel(真)
.setSound(defaultSoundUri)
.setContentIntent(挂起内容);
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.N)notificationBuilder.setPriority(NotificationManager.IMPORTANCE\u HIGH);
NotificationManager NotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION\u服务);
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.O){
NotificationChannel=新建NotificationChannel(channel ID,“MyApp”,NotificationManager.IMPORTANCE\u默认值);
如果(notificationManager!=null){
notificationManager.createNotificationChannel(频道);
}
}
如果(notificationManager!=null){
notificationManager.notify(id,notificationBuilder.build());
}
}
}

通过文档,您可以向客户端发送两种类型的消息:

通知消息-由FCM SDK自动处理

数据消息-由客户端应用程序处理

如果您想发送数据消息,请像这样实现FirebaseMessagingService(这只是一个示例,您可以使用它,但可以根据需要进行改进,还可以测试所有可能的解决方案以了解其工作原理)

公共类MyFirebaseMessagingService扩展了FirebaseMessagingService{
@凌驾
收到消息时公共无效(RemoteMessage RemoteMessage){
如果(remoteMessage.getData().size()>0){
handleDataMessage(remoteMessage.getData());
}else if(remoteMessage.getNotification()!=null){
//如果您不需要或不需要改进,请删除此行。。。
sendNotification(100,remoteMessage.getNotification().getBody());
}
}
私有void handleDataMessage(地图数据){
if(data.containsKey(“id”)和&data.containsKey(“消息”)){
字符串消息=data.get(“消息”);
int-id;
试一试{
id=Integer.parseInt(data.get(“id”));
}捕获(例外e){
e、 printStackTrace();
id=1;//服务器错误id的默认id或其他内容
}
发送通知(id、消息);
}
}
私有void sendNotification(int-id,字符串messageBody){
意向意向=新意向(此,MainActivity.class);
intent.addFlags(intent.FLAG\u ACTIVITY\u CLEAR\u TOP);
PendingEvent PendingEvent=PendingEvent.getActivity(this,0,intent,PendingEvent.FLAG_ONE_SHOT);
String channelId=“appChannelId”;//getString(R.String.default\u notification\u channel\u id);
Uri defaultSoundUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_通知);
NotificationCompat.Builder notificationBuilder=
新建NotificationCompat.Builder(此,channelId)
s
public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size() > 0) {
            handleDataMessage(remoteMessage.getData());
        }else if (remoteMessage.getNotification() != null) {
            //remove this line if you dont need or improve...
            sendNotification(100, remoteMessage.getNotification().getBody());
        }
    }

    private void handleDataMessage(Map<String, String> data) {
        if(data.containsKey("id") && data.containsKey("message")){
            String message = data.get("message");
            int id;
            try {
                id = Integer.parseInt(data.get("id"));
            }catch (Exception e){
                e.printStackTrace();
                id = 1; // default id or something else for wrong id from server
            }

            sendNotification(id, message);
        }
    }


    private void sendNotification(int id, String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent, PendingIntent.FLAG_ONE_SHOT);
        String channelId = "appChannelId"; //getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.icon) //TODO set your icon
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.iconpro_round)) //TODO set your icon
                        .setContentTitle("MyApp")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) notificationBuilder.setPriority(NotificationManager.IMPORTANCE_HIGH);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, "MyApp", NotificationManager.IMPORTANCE_DEFAULT);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
        if (notificationManager != null) {
            notificationManager.notify(id, notificationBuilder.build());
        }
    }
}
$fields = array (
    'to' => $device_id,
    'notification' => array(
      "title" => "New message from app",
      "body" => $message
    ),
);