Невозможно получить push-уведомление в конденсаторе с помощью FCMPhp

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Невозможно получить push-уведомление в конденсаторе с помощью FCM

Сообщение Anonymous »

Я создаю приложение с использованием CapacitorJS и Svelte с php Backend, моя проблема в том, что мне не удается реализовать push-уведомление, когда приложение находится в фоновом режиме (или закрыто)
вот мой манифест Android

Код: Выделить всё


















android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">




























здесь мой собственный класс Java, расширяющий firebaseCloudMessaging

Код: Выделить всё

package com.appapp.omi;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.capacitorjs.plugins.pushnotifications.PushNotificationsPlugin;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginHandle;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import com.getcapacitor.Bridge;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginManager;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "PushNotificationService";
private static final String CHANNEL_ID = "default_channel";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);

String title = "Default Title";
String body = "Default Body";

JSObject dataObj = new JSObject();

if (remoteMessage.getNotification() != null) {
title = remoteMessage.getNotification().getTitle();
body = remoteMessage.getNotification().getBody();
} else if (remoteMessage.getData().size() > 0) {
// Handle custom data payload
title = remoteMessage.getData().get("title");
body = remoteMessage.getData().get("body");

}

if (MainActivity.bridge != null) {
PluginHandle pushPluginHandle = MainActivity.bridge.getPlugin("PushNotifications");
if (pushPluginHandle != null) {
PushNotificationsPlugin pushPlugin = (PushNotificationsPlugin) pushPluginHandle.getInstance();
pushPlugin.fireNotification(remoteMessage);
}
//            MainActivity.bridge.triggerJSEvent("pushNotificationReceived", jsonString);
// MainActivity.bridge.triggerWindowJSEvent("pushNotificationReceived", data.toString());
} else {
Log.e("MyFirebaseService", "Bridge not initialized");
}
// Show notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.mipmap.ic_launcher) // Replace with your app's notification icon
.setPriority(NotificationCompat.PRIORITY_HIGH);

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
//    ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                                          int[] grantResults)
// to handle the case where the user grants the permission.  See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
notificationManager.notify(0, builder.build());
}

}
здесь моя реализация pushnotif в конденсаторе

Код: Выделить всё

export async function registerPushNotifications() {
try {

PushNotifications.requestPermissions().then((status) => {
console.log({status})
if (status.receive === 'granted') {
PushNotifications.addListener(
"pushNotificationReceived",
(notification) => {
console.log()
// console.log({notification: JSON.parse(notification)});
addGNotif(notification);
},
);

// Listener for errors
PushNotifications.addListener("registrationError", (error) => {
console.error("Push registration error:", error);
});

PushNotifications.addListener('pushNotificationActionPerformed', (action) => {
console.log(action)
alert("clicked")
});

FCM.getToken()
.then((r) => {
saveToken(r.token);
})
.catch((err) => console.log(err));
}
})

} catch (error) {
console.error('Push notification setup failed:', error);
}
}

вот мой серверный PHP

Код: Выделить всё

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;

function appapp_sendPushNotification($registrationTokens, $title, $body, $data = []) {
// Initialize Firebase
$factory = (new Factory)
->withServiceAccount(ABSPATH.DIRECTORY_SEPARATOR.'wp-content'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.'firebase-service-account.json'); // Optional if using Realtime Database

$messaging = $factory->createMessaging();

// Create the message
$message = CloudMessage::new()
->withNotification([
'title' => $title,
'body' => $body,
])->withTarget('token', $registrationTokens)->withHighestPossiblePriority()->withAndroidConfig(array('priority' => 'high', 'notification' => [
'title' => $title,
'body' => $body,
], 'data' => $data));

try {
$response = $messaging->send($message);
// $response = $messaging->sendMulticast($message, $registrationTokens);
error_log(json_encode($response));
return $response;
} catch (\Throwable $e) {
error_log($e->getMessage());

return $e->getMessage();
}
}

когда приложение находится на переднем плане, уведомление приходит, но не в фоновом режиме

Подробнее здесь: https://stackoverflow.com/questions/793 ... -using-fcm
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»