@@ -18,6 +18,7 @@ package com.duckduckgo.mobile.android.vpn.service
1818
1919import android.annotation.SuppressLint
2020import android.app.ActivityManager
21+ import android.app.ForegroundServiceStartNotAllowedException
2122import android.app.Service
2223import android.content.ComponentName
2324import android.content.Context
@@ -815,7 +816,7 @@ class TrackerBlockingVpnService : VpnService(), CoroutineScope by MainScope(), V
815816 if (! isServiceRunning(appContext)) return
816817
817818 snoozeIntent(appContext, triggerAtMillis).run {
818- ContextCompat .startForegroundService(appContext, this )
819+ appContext.startForegroundServiceWithFallback( this )
819820 }
820821 }
821822
@@ -842,7 +843,7 @@ class TrackerBlockingVpnService : VpnService(), CoroutineScope by MainScope(), V
842843 if (isServiceRunning(applicationContext)) return
843844
844845 startIntent(applicationContext).run {
845- ContextCompat .startForegroundService(applicationContext, this )
846+ applicationContext.startForegroundServiceWithFallback( this )
846847 }
847848 }
848849
@@ -852,15 +853,15 @@ class TrackerBlockingVpnService : VpnService(), CoroutineScope by MainScope(), V
852853 if (! isServiceRunning(applicationContext)) return
853854
854855 stopIntent(applicationContext).run {
855- ContextCompat .startForegroundService(applicationContext, this )
856+ applicationContext.startForegroundServiceWithFallback( this )
856857 }
857858 }
858859
859860 private fun restartService (context : Context ) {
860861 val applicationContext = context.applicationContext
861862
862863 restartIntent(applicationContext).run {
863- ContextCompat .startForegroundService(applicationContext, this )
864+ applicationContext.startForegroundServiceWithFallback( this )
864865 }
865866 }
866867
@@ -883,6 +884,22 @@ class TrackerBlockingVpnService : VpnService(), CoroutineScope by MainScope(), V
883884 }
884885 }
885886
887+ private fun Context.startForegroundServiceWithFallback (intent : Intent ) {
888+ try {
889+ ContextCompat .startForegroundService(this , intent)
890+ } catch (ex: ForegroundServiceStartNotAllowedException ) {
891+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .S ) {
892+ try {
893+ this .startService(intent)
894+ } catch (_: Throwable ) {
895+ // no-op
896+ }
897+ } else {
898+ throw ex
899+ }
900+ }
901+ }
902+
886903 private const val ACTION_START_VPN = " ACTION_START_VPN"
887904 private const val ACTION_STOP_VPN = " ACTION_STOP_VPN"
888905 private const val ACTION_RESTART_VPN = " ACTION_RESTART_VPN"
0 commit comments