Здравствуйте, вот код моего сервиса:
[Service(Exported = true, Name = "com.test.Foreground", ForegroundServiceType = Android.Content.PM.ForegroundService.TypeLocation)]
public class Foreground : Service, IServices
{
public override IBinder OnBind(Intent intent)
{
throw new NotImplementedException();
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
if (intent.Action == "START_SERVICE")
{
RegisterNotification();
}
else if (intent.Action == "STOP_SERVICE")
{
StopForeground(true);
StopSelfResult(startId);
}
return StartCommandResult.NotSticky;
}
public void Start()
{
Intent startService = new Intent(MainActivity.ActivityCurrent, typeof(Foreground));
startService.SetAction("START_SERVICE");
MainActivity.ActivityCurrent.StartService(startService);
}
public void Stop()
{
Intent stopIntent = new Intent(MainActivity.ActivityCurrent, this.Class);
nextTask.Dispose();
stopIntent.SetAction("STOP_SERVICE");
MainActivity.ActivityCurrent.StartService(stopIntent);
private async void RegisterNotification()
{
NotificationChannel channel = new NotificationChannel("Channel_Service", "Сервис работает!", NotificationImportance.Max);
NotificationManager manager = (NotificationManager)MainActivity.ActivityCurrent.GetSystemService(Context.NotificationService);
manager.CreateNotificationChannel(channel);
Notification notification = new Notification.Builder(this, "Channel_Service")
.SetContentTitle("Сервис работает!")
.SetSmallIcon(Microsoft.Maui.Resource.Drawable.default)
.SetOngoing(true)
.Build();
StartForeground(100, notification);
await Task.Run(async() => await nextTask.Main()); // после запуска открываю поток для моей задачи, которую я хочу выполнять во время работы сервиса.
}
}
Интерфейс IServices нужен для простого запуска сервиса по методу.
Дело в том, что сервис работает около 30-40 минут, а затем прекращает свою работу.
Мне было бы очень интересно узнать, как создают сервисы, которые работают всегда? Например Spotify, GoodByeDPI?
Почему тот же GoodByeDPI работает 24/7 и android не останавливает его?
Заранее спасибо за помощь!