Fixed ForegroundServiceStartNotAllowedException when song ended on Android 12.

This was due to Android 12's foreground service restrictions.
This commit is contained in:
Prathamesh More 2021-11-28 13:37:48 +05:30
parent 21a2014385
commit a78100c0ea
3 changed files with 12 additions and 2 deletions

View file

@ -9,7 +9,7 @@ android {
defaultConfig { defaultConfig {
minSdkVersion 21 minSdkVersion 21
targetSdkVersion 30 targetSdkVersion 31
renderscriptTargetApi 29//must match target sdk and build tools renderscriptTargetApi 29//must match target sdk and build tools
vectorDrawables.useSupportLibrary = true vectorDrawables.useSupportLibrary = true

View file

@ -262,6 +262,7 @@
android:enabled="true" android:enabled="true"
android:exported="true" android:exported="true"
android:label="@string/app_name" android:label="@string/app_name"
android:foregroundServiceType="mediaPlayback"
tools:ignore="ExportedService"> tools:ignore="ExportedService">
<intent-filter> <intent-filter>
<action android:name="android.media.browse.MediaBrowserService" /> <action android:name="android.media.browse.MediaBrowserService" />

View file

@ -19,6 +19,7 @@ import android.app.Notification
import android.app.NotificationChannel import android.app.NotificationChannel
import android.app.NotificationManager import android.app.NotificationManager
import android.content.Context.NOTIFICATION_SERVICE import android.content.Context.NOTIFICATION_SERVICE
import android.content.pm.ServiceInfo
import android.os.Build import android.os.Build
import androidx.annotation.RequiresApi import androidx.annotation.RequiresApi
import code.name.monkey.retromusic.R import code.name.monkey.retromusic.R
@ -62,7 +63,15 @@ abstract class PlayingNotification {
} }
if (newNotifyMode == NOTIFY_MODE_FOREGROUND) { if (newNotifyMode == NOTIFY_MODE_FOREGROUND) {
service.startForeground(NOTIFICATION_ID, notification) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
service.startForeground(
NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
)
} else {
service.startForeground(NOTIFICATION_ID,notification)
}
} else if (newNotifyMode == NOTIFY_MODE_BACKGROUND) { } else if (newNotifyMode == NOTIFY_MODE_BACKGROUND) {
notificationManager!!.notify(NOTIFICATION_ID, notification) notificationManager!!.notify(NOTIFICATION_ID, notification)
} }