Создание фоновой службы Android
Задача состоит в создании фоновой службы на платформе Android. При этом не должно быть вообще никакого UI, кроме постоянного уведомления в трее, информирующего о том, что служба запущена и работает.
- Проблема 1: Как полностью убрать UI? Я использую шаблон Blank App и не понимаю что нужно сделать, чтобы окно совсем не отображалось даже при запуске на мгновение. Приложение чисто должно запустить сервис и всё.
- Проблема 2: Запуск Foreground сервиса. Это должен быть насколько возможно "неубиваемый" сервис. Сейчас проблема видимо с вызовом
StartForeground(на моменте регистрации приложение падает.
Содержимое OnStartCommand:
void CreateNotificationChannel() {
if (Build.VERSION.SdkInt < BuildVersionCodes.O) return;
var channel = new NotificationChannel(CHANNEL_ID, channel_name, NotificationImportance.Default) {
Description = description
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId) {
CreateNotificationChannel();
var builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.SetContentTitle("Title")
.SetSmallIcon(Resource.Mipmap.ic_launcher)
.SetContentText("Content text")
.SetOngoing(true);
StartForeground(NOTIF_ID, builder.Build()); // Crash here
return StartCommandResult.NotSticky;
}
Запуск сервиса:
protected override void OnCreate(Bundle savedInstanceState) {
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.activity_main);
this.StartForegroundServiceCompat<BackgroundService>();
}
Метод расширения:
public static void StartForegroundServiceCompat<T>(this Context context, Bundle args = null) where T : Service {
Intent intent = new Intent(context, typeof(T));
if (args != null) intent.PutExtras(args);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O) context.StartForegroundService(intent);
else context.StartService(intent);
}
С проблемой №2 вроде удалось разобраться. При вызове StartForeground вылетало исключение Permission Denial - просто добавил в манифесте необходимое разрешение
FOREGROUND_SERVICE. Сервис действительно продолжает работу после закрытия окна приложения. Однако, его можно закрыть через раздел Работающие службы в настройках.