/messagesdess >.s.codes>. Я отправляю запрос «Только данные», он работает нормально, и я сам обращаюсь, я создаю локальное уведомление, отправляю пользователю и создаю свои собственные намерения и устанавливаю, поэтому, когда такое уведомление отправлено, оно является кликабельным и вскрытым запускается должным образом. Но этот запрос «только для данных» работает только тогда, когда мое приложение находится на фоне или на переднем плане, но когда мое приложение закрыто, оно не работает. Однако, когда мое приложение закрыто, я все еще могу видеть уведомление «только уведомление» или «Микш» (Notfication + Data) в лотке уведомления системы, но когда пользователь нажимает на него, оно уходит молча, ничего не делая. Моя точка останова никогда не нажимает на onnewintent или в onnotificationopened .
Это то, как выглядит мои полезные нагрузки:
только
Код: Выделить всё
{
"message": {
"token": "",
"notification": {
"title": "",
"body": ""
},
"android": {
"priority": "high",
"notification": {
"click_action": "FCM_CUSTOM_NOTIFICATION_CLICK"
}
}
}
}
< /code>
mixed < /p>
{
"message": {
"token": "",
"notification": {
"title": "",
"body": ""
},
"data": {
"": "",
"": "",
...
},
"android": {
"priority": "high",
"notification": {
"click_action": "FCM_CUSTOM_NOTIFICATION_CLICK"
}
}
}
}
[Activity(Label = "FCMCustom", LaunchMode = LaunchMode.SingleTop, Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]
[IntentFilter(new[] { "FCM_CUSTOM_NOTIFICATION_CLICK" }, Categories = new[] { "android.intent.category.DEFAULT" })]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
public static MainActivity Instance { get; private set; }
const string TAG = "FirebaseToken"; // Tag for Logcat
protected override async void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set the instance to this activity
//
try
{
FirebaseApp.InitializeApp(this);
}
catch (Exception ex)
{
Console.WriteLine("Error In FireBase");
}
Instance = this;
// Initialize Firebase Push Notification
try
{
FirebasePushNotificationManager.Initialize(this, false);
}
catch (Exception ex)
{
Console.WriteLine($"Error initializing FirebasePushNotification: {ex.Message}");
}
Plugin.FirebasePushNotification.CrossFirebasePushNotification.Current.OnTokenRefresh += (s, p) =>
{
//
FirebaseSettings.FirebaseToken = p.Token;
FirebaseSettings.IsFirebaseTokenUpdated = true;
//
SubscribeToAllTopic();
};
await GetFirebaseTokenAsync();
//GetFirebaseToken();
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
//
SubscribeToAllTopic();
Plugin.FirebasePushNotification.CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
{
DecideWhatToDoWithFireBaseCall(p.Data);
};
Plugin.FirebasePushNotification.CrossFirebasePushNotification.Current.OnNotificationOpened += (s, p) =>
{
System.Diagnostics.Debug.WriteLine("
};
// Process initial intent (for killed state)
ProcessNotificationIntent(Intent);
// Check and request notification permissions
CheckAndRequestNotificationPermission();
// Schedule the background worker
WorkerScheduler.ScheduleSyncWorker(this, false);
}
private void ProcessNotificationIntent(Intent intent)
{
FirebasePushNotificationManager.ProcessIntent(this, intent);
}
private void SubscribeToAllTopic()
{
try
{
//Plugin.FirebasePushNotification.CrossFirebasePushNotification.Current.Subscribe(FirebaseSettings.Topic_All);
Console.WriteLine("Subscribed to 'All' topic for global notifications");
}
catch (Exception ex)
{
Console.WriteLine($"Error subscribing to 'All' topic: {ex.Message}");
}
}
private void DecideWhatToDoWithFireBaseCall(IDictionary data)
{
try
{
if (data != null && data.Count > 0)
{
foreach (var item in data)
{
if (item.Key == "ND")
{
NotificationManagement notification = JsonConvert.DeserializeObject(item.Value.ToString());
if (notification != null)
{
if (notification.NotificationId > 0)
{
var result = NotificationUtility.InsertNotificationFromFB(notification);
if (notification.SendNow)
{
SendNow(notification);
}
}
else
{
//if notification Id is 0 then send only
SendNow(notification);
}
}
}
if (item.Key == "CN")
{
Content content = JsonConvert.DeserializeObject(item.Value.ToString());
if (content != null)
{
if (content.ContentId > 0)
{
var result = NotificationUtility.InsertUpdateCNFromFB(content);
}
}
}
if (item.Key == "UD")
{
UpdateManagement updateManagement = JsonConvert.DeserializeObject(item.Value.ToString());
if (updateManagement != null)
{
var result = NotificationUtility.InsertUpdateUMFromFB(updateManagement);
}
}
else if (item.Key == "AW")//intention is to awake only
{
AwakeKilledApp();
}
}
}
}
catch (Exception ex)
{
//don't let app kill if there is an error
Log.Error("Err", $"Error DecideWhatToDoWithFireBaseCall: {ex.Message}");
}
}
private void AwakeKilledApp()
{
try
{
var storedSyncRunDuration = FirebaseSettings.GetLastRunSyncRun();
if (storedSyncRunDuration != 0)
{
//see if the service was stopped for a long time
if (WorkerState.ShouldStartTimer(storedSyncRunDuration))
{
//if service was killed, awake it again
WorkerScheduler.ScheduleSyncWorker(this, false);
}
}
else
{
// Schedule the background worker from very start
WorkerScheduler.ScheduleSyncWorker(this, false);
}
}
catch (Exception ex)
{
Log.Error("Err", $"Error AwakeKilledApp: {ex.Message}");
}
}
private void SendNow(NotificationManagement notification)
{
//if notification Id is 0 then send only
if (notification.IsMandatory)
{
// if important, I will create a dynamic channel to send it
NotificationHelper.SendImportantNotification(this, notification);
}
else
{
//I will send it based on channel Type id - if user has switched on this channel
NotificationHelper.SendNotification(this, notification);
}
// Step 3: After sending, update notification status
if (notification.NotificationId != 0)
{
UpdateNofication(notification);
}
}
private async void UpdateNofication(NotificationManagement notification)
{
await NotificationUtility.UpdateNotificationStatus(notification, Helper.NotificationUpdateSource.Sent);
}
private async System.Threading.Tasks.Task GetFirebaseTokenAsync()
{
try
{
var tokenNow = await FirebaseMessaging.Instance.GetToken();
var latestToken = tokenNow?.ToString();
var existingToken = FirebaseSettings.FirebaseToken;
// Case 1: If existing token is empty, save the new token
if (string.IsNullOrWhiteSpace(existingToken))
{
FirebaseSettings.FirebaseToken = latestToken;
FirebaseSettings.IsFirebaseTokenUpdated = true;
return;
}
// Case 2: If token has changed, update and flag it
if (!string.IsNullOrWhiteSpace(latestToken) && !existingToken.Equals(latestToken))
{
FirebaseSettings.FirebaseToken = latestToken;
FirebaseSettings.IsFirebaseTokenUpdated = true;
}
// Case 3: If tokens match, do nothing
}
catch (Exception ex)
{
Console.WriteLine("Failed to get Firebase token: " + ex.Message);
}
}
protected async override void OnNewIntent(Intent intent)
{
try
{
base.OnNewIntent(intent);
// Process initial intent (for killed state)
ProcessNotificationIntent(intent);
if (intent.HasExtra("NOTIFICATION_DATA"))
{
int notificationId = intent.GetIntExtra("NOTIFICATION_DATA", -1);
await NotificationHelper.NavigateToPageBasedOnNotification(notificationId);
}
}
catch (Exception ex)
{
//don't let app die because of an error
}
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void CheckAndRequestNotificationPermission()
{
if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu) // Android 13+
{
if (CheckSelfPermission(Android.Manifest.Permission.PostNotifications) != Permission.Granted)
{
if (ShouldShowRequestPermissionRationale(Android.Manifest.Permission.PostNotifications))
{
RequestPermissions(new[] { Android.Manifest.Permission.PostNotifications }, 100);
}
else
{
ShowPermissionDeniedDialog();
}
}
}
}
private void ShowPermissionDeniedDialog()
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Notification Permission Needed");
alert.SetMessage("Please go to settings and enable notifications for this app.");
alert.SetPositiveButton("Open Settings", (senderAlert, args) =>
{
// Open app settings
Intent intent = new Intent(Android.Provider.Settings.ActionApplicationDetailsSettings);
intent.AddFlags(ActivityFlags.NewTask);
var uri = Android.Net.Uri.FromParts("package", PackageName, null);
intent.SetData(uri);
StartActivity(intent);
});
alert.SetNegativeButton("Cancel", (senderAlert, args) => { /* User chose to ignore */ });
alert.Show();
}
}
< /code>
И вот моя конфигурация < /p>
< /code>
Я попробовал почти все, и я ожидаю, что Onnotificationoped или Onnewintent следует стрелять, когда я отправляю сообщение Firebase of type 'только уведомление' или Mix (уведомление + данные). Но ни один из них не стреляет, по крайней мере, MainActity должна стрелять, чтобы я мог проверить, что недавно, и показать пользователю предпринять действие.
Подробнее здесь: https://stackoverflow.com/questions/795 ... mixed-fire