Browse Source

When stopping PlayerService, do not use foreground service api

Sending async message to the service using foreground API
requires setting foreground flag. This won't happen if
the service is being stopped, so we must use startService()
API instead.

This API will throw IllegalStateException when app is banned
from running a service due to power management constraints.

Since stopping a service under such condition is not needed
anyway (it is not running), we can safely catch and ignore it.

This happens when app is woken up after long inactivity and
UI is recreated from cache.

Fixes #9491

Signed-off-by: Chris Narkiewicz <hello@ezaquarii.com>
Chris Narkiewicz 3 years ago
parent
commit
989b8aeddb

+ 0 - 1
src/main/java/com/nextcloud/client/media/PlayerService.kt

@@ -152,7 +152,6 @@ class PlayerService : Service() {
 
     private fun onActionStopFile(args: Bundle?) {
         val file: OCFile = args?.getParcelable(EXTRA_FILE) ?: throw IllegalArgumentException("Missing file argument")
-
         stopServiceAndRemoveNotification(file)
     }
 

+ 13 - 2
src/main/java/com/nextcloud/client/media/PlayerServiceConnection.kt

@@ -28,6 +28,7 @@ import android.os.IBinder
 import android.widget.MediaController
 import com.nextcloud.client.account.User
 import com.owncloud.android.datamodel.OCFile
+import java.lang.IllegalStateException
 
 @Suppress("TooManyFunctions") // implementing large interface
 class PlayerServiceConnection(private val context: Context) : MediaController.MediaPlayerControl {
@@ -64,13 +65,23 @@ class PlayerServiceConnection(private val context: Context) : MediaController.Me
         val i = Intent(context, PlayerService::class.java)
         i.putExtra(PlayerService.EXTRA_FILE, file)
         i.action = PlayerService.ACTION_STOP_FILE
-        startForegroundService(i)
+        try {
+            context.startService(i)
+        } catch (ex: IllegalStateException) {
+            // https://developer.android.com/about/versions/oreo/android-8.0-changes#back-all
+            // ignore it - the service is not running and does not need to be stopped
+        }
     }
 
     fun stop() {
         val i = Intent(context, PlayerService::class.java)
         i.action = PlayerService.ACTION_STOP
-        startForegroundService(i)
+        try {
+            context.startService(i)
+        } catch (ex: IllegalStateException) {
+            // https://developer.android.com/about/versions/oreo/android-8.0-changes#back-all
+            // ignore it - the service is not running and does not need to be stopped
+        }
     }
 
     private val connection = object : ServiceConnection {