The Code A works well in Android 13 or low, but I get the Error A when I run it in Android 14?
How can I fix it?
Code A
private fun startForegroundService() {
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val mChannelName = getString(R.string.app_name)
val notificationManager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationChannel = NotificationChannel(
CHANNEL_ID,
mChannelName,
NotificationManager.IMPORTANCE_LOW
)
notificationManager.createNotificationChannel(notificationChannel)
NotificationCompat.Builder(this, notificationChannel.id)
} else {
NotificationCompat.Builder(this)
}
val myIntent = Intent(this, ActivityMain::class.java)
myIntent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(
this,
0,
myIntent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
builder.setSmallIcon(R.drawable.notify_icon)
.setContentTitle(getString(R.string.notificationTitle))
.setTicker(getString(R.string.notificationTicker )) //It will show text on status bar, even without having user to "pull down" the incoming notification.
.setContentText(getString(R.string.notificationContent))
.setContentIntent(pendingIntent)
val notification = builder.build()
notification.flags = notification.flags or NotificationCompat.FLAG_ONGOING_EVENT or NotificationCompat.FLAG_NO_CLEAR
startForeground(125, notification)
}
Error A
android.app.MissingForegroundServiceTypeException: Starting FGS without a type callerApp=ProcessRecord{8eb0601 12195:com.hicalc.soundrecorder/u0a190} targetSDK=34
at android.app.MissingForegroundServiceTypeException$1.createFromParcel(MissingForegroundServiceTypeException.java:53)
at android.app.MissingForegroundServiceTypeException$1.createFromParcel(MissingForegroundServiceTypeException.java:49)
at android.os.Parcel.readParcelableInternal(Parcel.java:4870)
From Android 14 (sdk 34) you have to set foreground service type. https://developer.android.com/about/versions/14/changes/fgs-types-required#permission-for-fgs-type
Check SDK version when attempting to go foreground:
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
startForeground(SERVICE_ID, notification)
} else {
startForeground(SERVICE_ID, notification,
FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK)
}
and update the manifest:
<uses-permission
android:name="android.permission.FOREGROUND_SERVICE_xxx"
android:minSdkVersion="34" />
<application ...>
<service
android:name=".feature.exerciseplayer.data.service.YourService"
android:exported="true"
android:foregroundServiceType="xxx" />
Note: replace xxx
by the service type that suits you.