개발 창고/Android

[Kotlin] "Vibrator" 사용하는 방법

로이제로 2023. 7. 19. 22:00
반응형

1. AndroidManifest.xml 설정

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="패키지명">
    ...
    <uses-permission android:name="android.permission.VIBRATE" />
    ...
</manifest>

어플에서 진동을 사용하기 위해 권한을 추가해 줍니다.

 

2. Vibrator 객체 생성

/**
 * @description 진동 객체 반환
 * @param   context     해당 컨텍스트
 */
fun getVibrator(context:Context):Vibrator{
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return context.getSystemService(Vibrator::class.java)
    }else{
        @Suppress("DEPRECATION")
        return context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    }
}

Android 버전이 API23 (Ver. M) 기준으로 호출 방식이 변경되었습니다.

 

3. Vibrator 실행

/**
 * @description 진동 시작
 * @param   context     해당 컨텍스트
 * @param   duration    진동 간격 (ms)
 */
fun startVibrate(context:Context, duration:Long){
    val vibrator:Vibrator = getVibrator(context)

    if(vibrator.hasVibrator())  vibrator.cancel()

    // 1. 진동 구현: 1분(1 * 60초 * 1000ms)동안 duration 진동 간격의 255강도로 진동
    val time            = ceil(1 * 60 * 1000.0 / duration).toInt()
    val timings         = Array(time) { duration }
    val amplitudes      = Array(time) { if (Math.floorMod(it, 2) == 0) 0 else 255 }
    val repeat          = -1   // -1은 반복 안함, 0은 반복

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        vibrator.vibrate(VibrationEffect.createWaveform(timings.toLongArray(), amplitudes.toIntArray(), repeat))
    } else {
        @Suppress("DEPRECATION")
        vibrator.vibrate(longArrayOf(duration, duration), repeat)
    }
}

만약 duration이 100ms라고 가정하면, 이는 1분동안

time = 600 = 1 * 60 * 1000.0 / 100

600번 반복 (진동/멈춤 반복)을 하게 되므로 총 진동 수는 300번이 됩니다.

timing = { 100, 100, 100, 100, ... }

amplitudes = { 0, 255, 0, 255, ... }

때문에 600번에 걸쳐 100ms씩 진동 크기가 0과 255를 반복하게 됩니다.

 

4. Vibrator 중지

/**
 * @description 진동 중지
 * @param   context     해당 컨텍스트
 */
fun stopVibrate(context:Context){
    val vibrator:Vibrator = getVibrator(context)

    vibrator.cancel()
}

 

시스템에서 가져온 vibrator service의 실행을 중지합니다.

 

※ 이 글은 워드프레스에 작성한 글과 동일한 작성자의 동일한 글입니다.

https://royfactory.net/2023/06/29/kotlin-use-vibrator/

 

[Kotlin] How to use “Vibrator” - ROY FACTORY

What should I do if I want to use vibration in an app made with Kotlin?

royfactory.net

 

반응형