diff --git a/app/src/main/java/be/ppareit/swiftp/FsService.java b/app/src/main/java/be/ppareit/swiftp/FsService.java index 3e19e5ae..f79221f6 100644 --- a/app/src/main/java/be/ppareit/swiftp/FsService.java +++ b/app/src/main/java/be/ppareit/swiftp/FsService.java @@ -21,6 +21,7 @@ package be.ppareit.swiftp; import android.app.AlarmManager; +import android.app.ForegroundServiceStartNotAllowedException; import android.app.PendingIntent; import android.app.Service; import android.content.Context; @@ -123,7 +124,16 @@ public static void start() { Context context = App.getAppContext(); Intent serviceIntent = new Intent(context, FsService.class); if (!FsService.isRunning()) { - ContextCompat.startForegroundService(context, serviceIntent); + + if (Build.VERSION.SDK_INT >= 31) { + try { + ContextCompat.startForegroundService(context, serviceIntent); + } catch (ForegroundServiceStartNotAllowedException e) { + // + } + } else { + ContextCompat.startForegroundService(context, serviceIntent); + } } } diff --git a/app/src/main/java/be/ppareit/swiftp/gui/FsWidgetProvider.java b/app/src/main/java/be/ppareit/swiftp/gui/FsWidgetProvider.java index 681095d6..560e5389 100644 --- a/app/src/main/java/be/ppareit/swiftp/gui/FsWidgetProvider.java +++ b/app/src/main/java/be/ppareit/swiftp/gui/FsWidgetProvider.java @@ -18,6 +18,7 @@ ******************************************************************************/ package be.ppareit.swiftp.gui; +import android.app.ForegroundServiceStartNotAllowedException; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; @@ -57,8 +58,7 @@ public void onReceive(Context context, Intent intent) { // watch for the broadcasts by the ftp server and update the widget if needed final String action = intent.getAction(); if (FsService.ACTION_STARTED.equals(action) || FsService.ACTION_STOPPED.equals(action)) { - Intent updateIntent = new Intent(context, UpdateService.class); - ContextCompat.startForegroundService(context, updateIntent); + startService(context, new Intent(context, UpdateService.class)); } super.onReceive(context, intent); } @@ -68,8 +68,19 @@ public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Cat.d("onUpdated called"); // let the updating happen by a service - Intent updateIntent = new Intent(context, UpdateService.class); - ContextCompat.startForegroundService(context, updateIntent); + startService(context, new Intent(context, UpdateService.class)); + } + + private void startService(Context context, Intent updateIntent) { + if (Build.VERSION.SDK_INT >= 31) { + try { + ContextCompat.startForegroundService(context, updateIntent); + } catch (ForegroundServiceStartNotAllowedException e) { + // + } + } else { + ContextCompat.startForegroundService(context, updateIntent); + } } public static class UpdateService extends Service {