2
0

More than 1 year has passed since last update.

【Android】バイブを鳴らす【Kotlin】

Posted at

はじめに

音を鳴らす関係で記事を他にも書いているのでそちらも観てください。

ボタンを押したら音が鳴るようにする

MainActivity.kt
        val button: Button = findViewById<Button>(R.id.button)  // 1

        val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator // 2

        button.setOnClickListener {                        
            vibrator.vibrate(1000)                                // 3
        }

説明していきます。
1.Buttonの ID を取得
2.Vibrationは直接インスタンス化できないので次のようにgetSystemServiceからインスタンス化
3.vibrateメソッドを使いバイブを鳴らす。この時引数は鳴らしたい時間をミリ秒で指定。
また、バイブの鳴らし方をカスタマイズしたい場合は

    vibrator.vibrate(longArrayOf(1000, 1000, 3000, 3000), -1)

というように定義し、第一引数にそれぞれミリ秒で
(振動までの待ち時間1, 振動時間1, 振動までの待ち時間2, 振動時間2...)
といったように配列を渡します。
上の例では 1秒待って1秒バイブ 3秒待って3秒バイブといったパターンを指定
第二引数に
繰り返しの回数を、繰り返しをしない場合は-1を渡します。

参考

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0