Android Studio中按钮点击时的振动不起作用

d4so4syb  于 2022-11-16  发布在  Android
关注(0)|答案(1)|浏览(277)

我想添加振动功能到我的应用程序,只是想开始一个简单的振动,我尝试了很多od turtorias,但似乎没有一个工作

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

    val timer_button = findViewById<Button>(R.id.timer_button)
    val timer_text: EditText = findViewById<EditText>(R.id.time_text)
    val vibrator  = getSystemService(VIBRATOR_MANAGER_SERVICE) as VibratorManager

   timer_button.setOnClickListener {
       //val pattern = longArrayOf(0, 200, 100, 300)
       vibrator.getDefaultVibrator().vibrate(VibrationEffect.createOneShot(1000,VibrationEffect.DEFAULT_AMPLITUDE))
       Toast.makeText(this, vibrator.getDefaultVibrator().getId().toString(),Toast.LENGTH_SHORT).show()

   }}

我还向manifest.xml添加了振动权限

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

wribegjk1#

它适用于所有APIS

val vibration = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            val vbManager =
                getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
            vbManager.defaultVibrator
        } else {
            @Suppress("DEPRECATION")
            getSystemService(VIBRATOR_SERVICE) as Vibrator
        }
        if (vibration.hasVibrator()) {
            vibration.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
        }

相关问题