11package com.simplecityapps.shuttle.ui
22
33import android.Manifest
4+ import android.app.ForegroundServiceStartNotAllowedException
45import android.content.Intent
56import android.content.pm.PackageManager
67import android.os.Build
@@ -22,6 +23,7 @@ import kotlinx.coroutines.CoroutineScope
2223import kotlinx.coroutines.launch
2324import kotlinx.coroutines.tasks.await
2425import kotlinx.coroutines.withTimeout
26+ import timber.log.Timber
2527
2628@AndroidEntryPoint
2729class MainActivity : AppCompatActivity () {
@@ -41,7 +43,7 @@ class MainActivity : AppCompatActivity() {
4143 @AppCoroutineScope
4244 lateinit var scope: CoroutineScope
4345
44- lateinit var snowfallView: SnowfallView
46+ var snowfallView: SnowfallView ? = null
4547
4648 // Lifecycle
4749
@@ -76,7 +78,7 @@ class MainActivity : AppCompatActivity() {
7678 withTimeout(5000 ) {
7779 remoteConfig.fetchAndActivate().await()
7880 }
79- snowfallView.setForecast(remoteConfig.getDouble(" snow_forecast" ))
81+ snowfallView? .setForecast(remoteConfig.getDouble(" snow_forecast" ))
8082 }
8183 }
8284
@@ -104,15 +106,23 @@ class MainActivity : AppCompatActivity() {
104106
105107 private fun handleSearchQuery (intent : Intent ? ) {
106108 if (intent?.action == MediaStore .INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH ) {
107- ContextCompat .startForegroundService(
108- this ,
109- Intent (this , PlaybackService ::class .java).apply {
110- action = PlaybackService .ACTION_SEARCH
111- intent.extras?.let { extras ->
112- putExtras(extras)
109+ try {
110+ ContextCompat .startForegroundService(
111+ this ,
112+ Intent (this , PlaybackService ::class .java).apply {
113+ action = PlaybackService .ACTION_SEARCH
114+ intent.extras?.let { extras ->
115+ putExtras(extras)
116+ }
113117 }
118+ )
119+ } catch (e: IllegalStateException ) {
120+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .S && e is ForegroundServiceStartNotAllowedException ) {
121+ Timber .w(e, " Cannot start foreground service from search query - app may be in restricted state" )
122+ } else {
123+ throw e
114124 }
115- )
125+ }
116126 }
117127 }
118128}
0 commit comments