안드로이드 스튜디오

[안드로이드 스튜디오 코틀린] Vibrator VIBRATOR_SERVICE deprecated 대응

권송미 2023. 5. 17. 14:15
728x90
반응형

 

 

 

 

 

vibrator_manager_service service cast error 대응

 

 

 

 

초기화 방법 - > 

 

 

vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    val vibratorManager: VibratorManager = getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
    vibratorManager.defaultVibrator
} else {
    getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

코드 적용

 

 

 

 

 

 

 

 

 

 

 

 

 

AndroidManifest.xml

 

<uses-permission android:name="android.permission.VIBRATE"/>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

MainActivity.kt

 

 

import android.content.Context
import android.os.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    private lateinit var vibrator: Vibrator

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            val vibratorManager: VibratorManager = getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
            vibratorManager.defaultVibrator
        } else {
            getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        }
    }

    private fun getVibration() {
        val vibrationEffect = VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE)
        vibrator.vibrate(vibrationEffect)
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90
반응형