1 Commits
Author SHA1 Message Date
ivanszabo 3d0f9ce987 Saját notify 2025-05-14 20:12:25 +02:00
14 changed files with 179 additions and 139 deletions
+11 -2
View File
@@ -8,7 +8,15 @@ using WorkFlowCheck.MAUI.DataLayer;
using WorkFlowCheck.MAUI.Helper;
using WorkFlowCheck.MAUI.Services;
using WorkFlowCheck.MAUI.Services.Interfaces;
using Android.Content.PM;
using WorkFlowCheck.MAUI.Platforms.Android.Services;
#if ANDROID
using Android.Content;
using WorkFlowCheck.MAUI.Platforms.Android;
#endif
namespace WorkFlowCheck.MAUI
{
public partial class App : Application
@@ -29,14 +37,15 @@ namespace WorkFlowCheck.MAUI
_dbContext.Database.EnsureDeleted(); // Adatbázis törlése
_dbContext.Database.EnsureCreated(); // Új adatbázis létrehozása
StartBackgroundTask();
//StartBackgroundTask();
MainPage = new AppShell();
//MainPage = new NavigationPage(new MainPage(serviceProvider.GetRequiredService<IUserService>()));
}
protected async override void OnResume()
{
StartBackgroundTask();
//StartBackgroundTask();
base.OnResume();
var isLogged = await SecureStorage.Default.GetAsync("WFCUser");
if (isLogged == null)
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.MAUI.Helper
{
public static class ServiceHelper
{
public static IServiceProvider Services { get; set; }
}
}
+4 -1
View File
@@ -1,7 +1,9 @@
using DevExpress.Entity.Model.Metadata;
using Android.Content;
using DevExpress.Entity.Model.Metadata;
using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.MAUI.Helper;
using WorkFlowCheck.MAUI.Pages.Media;
using WorkFlowCheck.MAUI.Platforms.Android.Services;
using WorkFlowCheck.MAUI.Services.Interfaces;
namespace WorkFlowCheck.MAUI
{
@@ -15,6 +17,7 @@ namespace WorkFlowCheck.MAUI
{
InitializeComponent();
_userService = userService;
}
private void SetInfo()
+4 -21
View File
@@ -12,12 +12,7 @@ using Microsoft.Maui.Hosting;
using CommunityToolkit.Maui.Core;
using WorkFlowCheck.MAUI.Handlers;
using WorkFlowCheck.MAUI.Helper;
using Plugin.Firebase.CloudMessaging;
using Microsoft.Maui.LifecycleEvents;
#if ANDROID
using Plugin.Firebase.Core.Platforms.Android;
#endif
namespace WorkFlowCheck.MAUI
{
public static class MauiProgram
@@ -28,7 +23,7 @@ namespace WorkFlowCheck.MAUI
builder.UseDevExpress(useLocalization: false)
.UseDevExpressControls()
.UseDevExpressCollectionView();
builder.Services.AddAutoMapper(typeof(MapperProfile));
builder.Services.AddHttpClient();
builder.Services.AddDbContext<AppDbContext>();
@@ -51,7 +46,7 @@ namespace WorkFlowCheck.MAUI
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
fonts.AddFont("FontAwesome.ttf", "FontAwesome");
})
.RegisterFirebaseServices()
.UseMauiCommunityToolkitCore()
.UseMauiCommunityToolkit();
#if DEBUG
@@ -68,24 +63,12 @@ namespace WorkFlowCheck.MAUI
}).GetAwaiter().GetResult();
}
ServiceProvider = app.Services;
ServiceHelper.Services = app.Services;
return app;
}
public static IServiceProvider ServiceProvider { get; private set; }
private static MauiAppBuilder RegisterFirebaseServices(this MauiAppBuilder builder)
{
builder.ConfigureLifecycleEvents(events =>
{
#if ANDROID
events.AddAndroid(android => android.OnCreate((activity, _) =>
CrossFirebase.Initialize(activity)));
#endif
});
return builder;
}
}
}
@@ -1,9 +1,10 @@
using Android.Content;
using CommunityToolkit.Maui.Alerts;
using CommunityToolkit.Maui.Core;
using Plugin.Firebase.CloudMessaging;
using System.Drawing;
using WorkFlowCheck.MAUI.Helper;
using WorkFlowCheck.MAUI.Pages.NFC;
using WorkFlowCheck.MAUI.Platforms.Android.Services;
using WorkFlowCheck.MAUI.Services.Interfaces;
namespace WorkFlowCheck.MAUI.Pages.Security;
@@ -15,7 +16,6 @@ public partial class LoginPage : BasePage
public LoginPage()
{
InitializeComponent();
InitFirebase();
SetContent(LoginContent);
_userService = MauiProgram.ServiceProvider.GetRequiredService<IUserService>();
_syncService = MauiProgram.ServiceProvider.GetRequiredService<ISyncService>();
@@ -35,9 +35,13 @@ public partial class LoginPage : BasePage
if (response != null && response.IsSuccess)
{
_userService.SetCurrentUser(response.Data);
SystemHelper.SystemUserDTO = response.Data;
SystemHelper.SystemUserDTO = response.Data;
#if ANDROID
var intent = new Intent(Android.App.Application.Context, typeof(NotifyService));
Android.App.Application.Context.StartForegroundService(intent);
#endif
var wFCUser = Newtonsoft.Json.JsonConvert.SerializeObject(response.Data);
await SecureStorage.Default.SetAsync("WFCUser", "wFCUser");
@@ -168,23 +172,4 @@ public partial class LoginPage : BasePage
}
}
private async void InitFirebase()
{
try
{
await CrossFirebaseCloudMessaging.Current.CheckIfValidAsync();
var token = await CrossFirebaseCloudMessaging.Current.GetTokenAsync();
await _syncService.UploadFCMToken(token);
}
catch (Exception ex)
{
await SystemHelper.ShowSnackBar("FCM üzenetküldõ inicializálása SIKERTELEN!",
SystemHelper.ColorToHex(Colors.Red),
SystemHelper.ColorToHex(Colors.Red),
SystemHelper.ColorToHex(Colors.Yellow),
15);
}
}
}
@@ -15,21 +15,11 @@
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="default" />
<receiver
android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver"
android:exported="false" />
<receiver
android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
<service android:name="WorkFlowCheck.MAUI.Platforms.Android.Services.NotifyService"
android:enabled="true"
android:exported="true"
android:foregroundServiceType="dataSync"
android:process=":notiprocess"/>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
@@ -38,8 +28,7 @@
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
</manifest>
@@ -3,8 +3,6 @@ using Android.Content;
using Android.Content.PM;
using Android.Nfc;
using Android.OS;
using Firebase;
using Plugin.Firebase.CloudMessaging;
using Plugin.NFC;
@@ -36,21 +34,18 @@ namespace WorkFlowCheck.MAUI
protected override void OnCreate(Bundle savedInstanceState)
{
CrossNFC.Init(this);
Firebase.FirebaseApp.InitializeApp(this);
base.OnCreate(savedInstanceState);
nfcAdapter = NfcAdapter.GetDefaultAdapter(this);
pendingIntent = PendingIntent.GetActivity(this, 0,
new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.SingleTop),
Build.VERSION.SdkInt >= BuildVersionCodes.S ? PendingIntentFlags.Mutable : PendingIntentFlags.UpdateCurrent);
HandleIntent(Intent);
CreateNotificationChannelIfNeeded();
}
protected override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
HandleIntent(intent);
CrossNFC.OnNewIntent(intent);
if (intent.Action == NfcAdapter.ActionTagDiscovered)
@@ -90,24 +85,5 @@ namespace WorkFlowCheck.MAUI
// nfcAdapter?.DisableForegroundDispatch(this);
//}
}
private static void HandleIntent(Intent intent)
{
FirebaseCloudMessagingImplementation.OnNewIntent(intent);
}
private void CreateNotificationChannelIfNeeded()
{
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
CreateNotificationChannel();
}
}
private void CreateNotificationChannel()
{
var channelId = $"{PackageName}.general";
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
var channel = new NotificationChannel(channelId, "General", NotificationImportance.Default);
notificationManager.CreateNotificationChannel(channel);
FirebaseCloudMessagingImplementation.ChannelId = channelId;
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<string name="com.google.firebase.crashlytics.mapping_file_id">none</string>
</resources>
@@ -0,0 +1,124 @@
using Android.App;
using Android.Content;
using Android.OS;
using System.Threading;
using System.Threading.Tasks;
using WorkFlowCheck.MAUI.Helper;
using WorkFlowCheck.MAUI.Services.Interfaces;
namespace WorkFlowCheck.MAUI.Platforms.Android.Services
{
[Service]
public class NotifyService : Service
{
private CancellationTokenSource _cts;
private IUserService _userService;
private ISyncService _syncService;
public NotifyService()
{
}
public override IBinder OnBind(Intent intent) => null;
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
CreateNotificationChannel();
var notification = new Notification.Builder(this, "polling_channel")
.SetContentTitle("Értesítés figyelés")
.SetContentText("A háttérfigyelés aktív")
.SetSmallIcon(Resource.Drawable.notification_icon)
.SetVisibility(NotificationVisibility.Public) // Lock screen-en is látszódjon
.SetPriority((int)NotificationPriority.High)
.Build();
StartForeground(1, notification);
_cts = new CancellationTokenSource();
var _syncService = ServiceHelper.Services.GetService(typeof(ISyncService)) as ISyncService;
var _userService = ServiceHelper.Services.GetService(typeof(IUserService)) as IUserService;
Task.Run(async () =>
{
await _syncService.SyncUsers_Down((progress, message) =>
{
});
}, _cts.Token);
var userDTO = _userService.GetCurrentUser();
if (userDTO != null && userDTO.Id > 0)
{
if (userDTO.RoleDTO?.Count > 0)
{
foreach (var roleDTO in userDTO.RoleDTO)
{
if (roleDTO.CanEnableBlocked)
{
Task.Run(async () =>
{
while (!_cts.Token.IsCancellationRequested)
{
var deviceMessageDTOList = await _syncService.DeviceMessageReadUnreaded(_userService.DeviceId.ToUpper());
if (deviceMessageDTOList != null && deviceMessageDTOList.Count > 0)
{
ShowNotification("Új esemény", deviceMessageDTOList[0].Message);
break;
}
deviceMessageDTOList = await _syncService.DeviceMessageReadUnreadedRole(roleDTO.Id);
if (deviceMessageDTOList != null && deviceMessageDTOList.Count > 0)
{
ShowNotification("Új esemény", deviceMessageDTOList[0].Message);
break;
}
await Task.Delay(5000);
}
}, _cts.Token);
}
}
}
}
return StartCommandResult.Sticky;
}
public override void OnDestroy()
{
_cts?.Cancel();
base.OnDestroy();
}
private void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var channel = new NotificationChannel("polling_channel", "Polling Channel", NotificationImportance.High)
{
Description = "Foreground service polling channel",
LockscreenVisibility = NotificationVisibility.Public
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
}
private void ShowNotification(string title, string message)
{
var builder = new Notification.Builder(this, "polling_channel")
.SetContentTitle(title)
.SetContentText(message)
.SetSmallIcon(Resource.Drawable.notification_icon)
.SetAutoCancel(true)
.SetVisibility(NotificationVisibility.Public)
.SetPriority((int)NotificationPriority.High);
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(new System.Random().Next(), builder.Build());
}
}
}
@@ -26,7 +26,5 @@ namespace WorkFlowCheck.MAUI.Services.Interfaces
Task<ApiResponseDTO<string>> SyncUsers_Up(Action<double, string> reportProgress);
Task SyncUsers_Down(Action<double, string> reportProgress);
Task<bool> UploadFCMToken(string token);
}
}
@@ -512,40 +512,5 @@ namespace WorkFlowCheck.MAUI.Services
}
}
public async Task<ApiResponseDTO<bool>> UploadFCMToken(string token)
{
var retVal = new ApiResponseDTO<bool>();
try
{
string endpoint = $"{_httpClient.BaseAddress}api/fcm/SendFCMToken";
var FCMMessageDTO = new FCMMessageDTO()
{
Token = token,
UserId = _userService.GetCurrentUser()?.Id
};
using (HttpResponseMessage httpResponseMessage = await _httpClient.PostAsJsonAsync(endpoint, FCMMessageDTO))
{
httpResponseMessage.EnsureSuccessStatusCode();
var jsonString = await httpResponseMessage.Content.ReadAsStringAsync();
var response = JsonConvert.DeserializeObject<ApiResponseDTO<bool>>(jsonString);
return response ?? new ApiResponseDTO<bool>
{
IsSuccess = false,
};
}
}
catch (Exception ex)
{
// Hiba visszaadása
return new ApiResponseDTO<bool>
{
IsSuccess = false
};
}
}
}
}
@@ -31,14 +31,12 @@
<!--<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">11.0</SupportedOSPlatformVersion>-->
<!--<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'maccatalyst'">13.1</SupportedOSPlatformVersion>-->
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">21.0</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">29.0</SupportedOSPlatformVersion>
<!--<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</SupportedOSPlatformVersion>
<TargetPlatformMinVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</TargetPlatformMinVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'tizen'">6.5</SupportedOSPlatformVersion>-->
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0-android'">
<GoogleServicesJson Include="Platforms\Android\google-services.json" />
</ItemGroup>
<ItemGroup>
<!-- App Icon -->
<MauiIcon Include="Resources\AppIcon\appicon.svg" ForegroundFile="Resources\AppIcon\appiconfg.svg" Color="#512BD4" />
@@ -56,9 +54,6 @@
<!-- Raw Assets (also remove the "Resources\Raw" prefix) -->
<MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>
<ItemGroup>
<AndroidResource Remove="Platforms\Android\Resources\values\strings.xml" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Platforms\Android\Resources\xml\file_paths.xml" />
@@ -88,8 +83,6 @@
<PackageReference Include="Microsoft.Maui.Controls.Compatibility" Version="$(MauiVersion)" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Plugin.Firebase.Auth" Version="3.1.1" />
<PackageReference Include="Plugin.Firebase.CloudMessaging" Version="3.1.2" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.7" />
@@ -166,4 +159,10 @@
<Folder Include="Platforms\Android\Resources\mipmap-xxxhdpi\" />
</ItemGroup>
<ItemGroup>
<AndroidResource Update="Platforms\Android\Resources\drawable\notification_icon.png">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</AndroidResource>
</ItemGroup>
</Project>