skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.


  2. If you are using the stopForeground of ServiceCompat, following the documentation you need to change the stopForeground(Boolean) and pass either STOP_FOREGROUND_REMOVE or STOP_FOREGROUND_DETACH explicitly instead. Depending on your compileSDK it will complain or not, if you have compileSDK 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 this stopForeground, you should pass a Service and a flag

        public static void stopForeground(@NonNull Service service, @StopForegroundFlags int flags) {
            if (Build.VERSION.SDK_INT >= 24) {
                Api24Impl.stopForeground(service, flags);
            } else {
                service.stopForeground((flags & ServiceCompat.STOP_FOREGROUND_REMOVE) != 0);
            }
        }
    
        @RequiresApi(24)
        static class Api24Impl {
            private Api24Impl() {
                // This class is not instantiable.
            }
    
            @DoNotInline
            static void stopForeground(Service service, int flags) {
                service.stopForeground(flags);
            }
        }
    

    Internally they use this stopForeground

        @Deprecated
        public final void stopForeground(boolean removeNotification) {
            throw new RuntimeException("Stub!");
        }
    
        public final void stopForeground(int notificationBehavior) {
            throw new RuntimeException("Stub!");
        }
    

    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 the deprecation warning as follows

    enter image description here

    Try to Invalidate cache and restart to see that there’s not an IDE problem.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search