LoginSignup
1
0

More than 1 year has passed since last update.

Android12以上の振動(バイブレーション)の実装方法

Last updated at Posted at 2022-04-02

前回API level 26以上 API level 31未満のやり方を書きました。

今回は、API level 31の振動のさせ方を書こうと思います。

Manifestの設定

AndroidManifest.xmlでVIBRATEの許可します。

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

Activity

MainActivity.kt
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    val vibratorManager = getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
    val vibrationEffect = VibrationEffect.createWaveform(longArrayOf(500L, 1000L),intArrayOf(200, 0), -1)
    val combinedVibration = CombinedVibration.createParallel(vibrationEffect)
    vibratorManager.vibrate(combinedVibration)
}

これで振動できます。
VibrationEffect.createWaveformで振動の設定をします。

第一引数はタイミング/振幅ペアのタイミング値(ミリ秒単位)。タイミング値が0の場合、ペアは無視されます。
今回は500ms振動して1000ms振動しないとなります。

第二引数はタイミング/振幅ペアの振幅値。振幅値は、0〜255、またはに等しい必要があります。振幅値0は、オフであることを意味します。
今回は第一引数で設定した500msの間200の強さ振動をして、1000msの間0の強さの振動(オフ)となります。

第三引数は繰り返すタイミング配列へのインデックス。無期限に繰り返したくない場合は-1
今回は繰り返さないです。無限に繰り返す場合は0を入れてください。

※第一引数と第二引数のリストサイズは同じである必要があります。
※第三引数はリストのサイズまでの整数を入れる事ができます。

例:リストのサイズが5で第三引数に3を入れた場合
0->1->2->3->4->3->4->3->4

振動の設定が簡単にできるようになりました。

1
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
1
0