Maui: Android: Der Vordergrundservice läuft nicht
Posted: 30 Apr 2025, 18:45
Ich habe den Vordergrunddienst wie unten in meiner Maui -Anwendung integriert.
backgroundService.cs unter Plattforms.android
Erstellt eine Schnittstelle IbackgroundService in einzelnen Lösung:
Erlaubnis in AndroidManifest.xml
hinzugefügt
Was fehlt mir hier? Wenn sich die App jedoch im Hintergrund befindet, stoppt der Timer. Ich möchte den Timer ausführen und die Standortdetails senden, wenn sich die App im Vordergrund, im Hintergrund befindet und selbst wenn das Gerät gesperrt ist (App ist im Vordergrund oder im Hintergrund). Für die Implementierung versuche ich, die Vordergrunddienste in Android zu nutzen.
Code: Select all
// MyForegroundService.cs
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using AndroidX.Core.App;
using System.Threading.Tasks;
using Resource = Microsoft.Maui.Resource;
[Service(ForegroundServiceType = ForegroundService.TypeLocation)]
public class MyForegroundService : Service
{
private const int ServiceRunningNotificationId = 10000;
private bool isRunning = true;
public override void OnCreate()
{
base.OnCreate();
System.Diagnostics.Debug.WriteLine("MyForegroundService: OnCreate");
StartForeground(ServiceRunningNotificationId, BuildNotification());
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
System.Diagnostics.Debug.WriteLine("MyForegroundService: OnStartCommand");
Task.Run(async () =>
{
try
{
while (isRunning)
{
System.Diagnostics.Debug.WriteLine("MyForegroundService: Timer Tick");
await Task.Delay(10000);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("MyForegroundService crashed: " + ex.Message);
}
});
return StartCommandResult.Sticky;
}
public override IBinder OnBind(Intent intent) => null;
public override void OnDestroy()
{
isRunning = false;
base.OnDestroy();
}
Notification BuildNotification()
{
var channelId = "foreground_service_channel";
var channelName = "Background Timer";
var manager = (NotificationManager)GetSystemService(NotificationService);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var channel = new NotificationChannel(channelId, channelName, NotificationImportance.Default);
manager.CreateNotificationChannel(channel);
}
var notification = new NotificationCompat.Builder(this, channelId)
.SetContentTitle("Background Task Running")
.SetContentText("Your timer is active every 10 seconds.")
.SetSmallIcon(Resource.Drawable.ic_notification) // Replace with your icon
.SetOngoing(true)
.Build();
return notification;
}
}
Code: Select all
using AlertBuddies.Service;
using Android.Content;
using Android.OS;
using Microsoft.Maui.Controls;
using Android.App;
using Application = Android.App.Application;
using Android.Content.PM;
[assembly: Dependency(typeof(AlertBuddies.Platforms.Android.BackgroundService))]
namespace AlertBuddies.Platforms.Android
{
public class BackgroundService : IBackgroundService
{
public void Start()
{
System.Diagnostics.Debug.WriteLine("BackgroundService.Start() called");
var context = Application.Context;
var intent = new Intent(context, Java.Lang.Class.FromType(typeof(MyForegroundService)));
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
context.StartForegroundService(intent);
else
context.StartService(intent);
}
public void Stop()
{
var context = Application.Context;
var intent = new Intent(context, Java.Lang.Class.FromType(typeof(MyForegroundService)));
context.StopService(intent);
}
}
}
Code: Select all
public interface IBackgroundService
{
void Start();
void Stop();
}
hinzugefügt
Code: Select all
//added under application tag
< /code>
Schließlich habe ich den Dienst vom Hauptprojekt wie unten gestartet: < /p>
DependencyService.Get()?.Start();
< /code>
Nach dem Ausführen des Projekts geschieht nichts. Ich habe einen Debugger im Hintergrund hinzugefügt, und das wird auch im Ausgangsfeld nicht angezeigt. < /P>
System.Diagnostics.Debug.WriteLine("BackgroundService.Start() called");