Код: Выделить всё
// 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;
}
}
Код: Выделить всё
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);
}
}
}
Код: Выделить всё
public interface IBackgroundService
{
void Start();
void Stop();
}
Код: Выделить всё
//added under application tag
< /code>
Наконец -то я запустил службу из основного проекта, как ниже: < /p>
DependencyService.Get()?.Start();
< /code>
После запуска проекта ничего не происходит. Я добавил отладчик в фоновом сервисе, и это также не отображается в выходе. < /P>
System.Diagnostics.Debug.WriteLine("BackgroundService.Start() called");
Подробнее здесь: https://stackoverflow.com/questions/796 ... ot-running
Мобильная версия