Search code examples
androidandroid-looper

How to deal with deprecated funtion android/os/Looper#prepareMainLooper?


According to Android API: https://developer.android.com/reference/android/os/Looper#prepareMainLooper()

the prepareMainLooper() is deprecated in api level 30.

How should I do: A:

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
    Looper.prepareMainLooper()
} else {
    Looper.prepare()
}

B:

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
    Looper.prepareMainLooper()
}

A or B?


Solution

  • You should never call prepateMainLooper, in any version of Android. It should never have been a public function. It sets up the looper for the main thread. The framework does that for you, so it was never useful to call, and could even have caused damage. If you want to set up your own looper on your own thread, you call prepare on that thread. If you want to set up a looper on the main thread you do nothing, because it's already done for you, and has been since Android 1.0.