I have the following code. Why is the second stopForeground
highlighted as a deprecation warning in Android Studio ( Electric Eeel | 2022.1.1)?
class FooService : android.app.Service() {
fun bar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
stopForeground(STOP_FOREGROUND_REMOVE)
} else {
stopForeground(true) // This line shows as deprecated
}
}
}
I’m using compileSdk 33
and minSdk 21
targetSdk 33
and have Android SDK Build-Tools 34-rc1
installed.
2
Answers
The line is highlighted as deprecated because it is deprecated.
Whilst this is true, it seems strange to me to highlight this in a way that makes it look like an error or something to be avoided. This code is the standard of handling deprecated methods and so perhaps should not be highlighted in a way that makes it look like an error...the deprecated line only runs on api levels for which it wasn't deprecated.
If you are using the
stopForeground
ofServiceCompat
, following the documentation you need to change thestopForeground(Boolean)
and pass eitherSTOP_FOREGROUND_REMOVE
orSTOP_FOREGROUND_DETACH
explicitly instead. Depending on yourcompileSDK
it will complain or not, if you havecompileSDK 33
is going to complain since in the new api version they’ve changed the signature of that method.From source code of
ServiceCompat
you are trying to use thisstopForeground
, you should pass aService
and aflag
Internally they use this
stopForeground
So, try to use the import of
import androidx.core.app.ServiceCompat.stopForeground
and check if the error persists.In case you are doing this code inside a
Service
what you should see is thedeprecation
warning as followsTry to
Invalidate cache and restart
to see that there’s not an IDE problem.