Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'VIBRATOR_SERVICE: String' is deprecated for API 31

As the title says, i upgraded to API 31. I had a function to perform a vibration, but in the line

val vib = this.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator

the VIBRATOR_SERVICE is now shown as deprecated. How can i replace it? Or at least, what's the modern solution for API 31 and above?

EDIT: as Joachim Sauer wrote, the alternative is VibrationManager. What i need now is the equivalent line of code using VibrationManager.

like image 295
m.i.n.a.r. Avatar asked Dec 17 '22 11:12

m.i.n.a.r.


2 Answers

val vib = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    val vibratorManager =
        getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
    vibratorManager.defaultVibrator
} else {
    @Suppress("DEPRECATION")
    getSystemService(VIBRATOR_SERVICE) as Vibrator
}
like image 84
Farrukh Tulkunov Avatar answered Dec 21 '22 09:12

Farrukh Tulkunov


The docs for this field say this:

This constant was deprecated in API level 31. Use VibratorManager to retrieve the default system vibrator.

The most direct translation of code needing a Vibrator instance would be this:

val vibratorManager = this.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
val vibrator = vibratorManager.getDefaultVibrator();

Generally speaking whenever a class/method/field is deprecated like this then you should first check the documentation. Almost every single time it will tell you what to use instead (or in some cases that it has no replacement).

like image 25
Joachim Sauer Avatar answered Dec 21 '22 09:12

Joachim Sauer