본문 바로가기
🖥 Programming/📱 Android (Kotlin)

[Android][kotlin] 진동 울리기

by MinChan-Youn 2022. 3. 29.

안녕하세요~ 챠니입니다! :)

이번에는 Vibrate(진동) 에 대해서 알아보겠습니다~

어렵지 않으니 하나씩 따라오시면 되겠습니다 :)

Vibrate(진동)은 Android Native의 기능으로 Android application에서 울리기 위해서 사용되는 기능이라고 생각하면 되겠습니다.

 

    Vibrator란?

    Android에서 제공되는 Vibrator 객체를 이용하여 진동을 발생시킬 수 있습니다.

    https://developer.android.com/reference/android/os/Vibrator

     

    Vibrator  |  Android Developers

     

    developer.android.com

     

    ◼ vibrate(long milliseconds)

    정해진 시간동안 진동 발생 (Android O(26) 부터 deprecated 됨)

     

    ◼ vibrate(android.os.VibrationEffect)

    정해진 vibration effect 에 맞추어 진동 발생 (Android O(26) 부터 추가됨)

     

    ◼ VibrationEffect.createOneShot(long milliseconds, int amplitude)

    1회 진동을 울릴 경우 사용

     - milliseconds : 진동 시간

     - amplitude : 진동의 세기, 기본값은 DEFAULT_AMPLITUDE, 지정 값은 1 ~ 255.

     

    ◼ VibrationEffect.createWaveform(long[] timings, int[] amplitudes, int repeat)

    반복하여 진동을 울릴 때 사용

     - timings : 진동의 패턴으로 반드시 짝수 개수로 작성. (배열 중 홀수 값 : 대기시간 / 짝수 값 : 진동 시간)

     - amplitudes : 진동의 세기. 생략 가능 (생략하는 경우 default 값으로 지정)

     - repeat : 진동 반복 여부. 진동을 중지하고 싶다면 cancel() 로 취소 가능.

    -1 : 반복 하지 않는다.

    0 : 주어진 패턴을 모두 반복

    1 : 처음 패턴 후 해당 인덱스 위치의 패턴 반복 으로 계속 반복.

    2 : 이 한 번 울린 후 으로 계속 반복.

     

     

    소스코드

    *AndroidManifest.xml

    - VIBRATE 퍼미션 추가

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.vibrate_kotlin">
    
        <!-- Vibrate -->
        <uses-permission android:name="android.permission.VIBRATE"/>
    
        <application
            android:allowBackup="true"
            ...
            ...

     

     

    *MainAtivirty.kt

    - ClickListener에 따른 진동 기능 설정

    class MainActivity : AppCompatActivity() {
        lateinit var binding: ActivityMainBinding
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = ActivityMainBinding.inflate(layoutInflater)
            setContentView(binding.root)
    
            initVibrate()
        }
    
        private fun initVibrate() {
            var vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    
            /** 진동 - 1번 */
            binding.tvVibrateOneshot.setOnClickListener {
                // 1초 진동 울리기
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    vibrator.vibrate(VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE))
                } else {
                    vibrator.vibrate(1000);
                }
                Toast.makeText(applicationContext, "진동 1회", Toast.LENGTH_SHORT).show()
            }
    
            /** 진동 - 패턴 */
            binding.tvVibratePattern.setOnClickListener {
                // 1초 대기 -> 1초 진동 -> 1초 대기 -> 1초 진동
                val vibratePattern = longArrayOf(1000, 1000, 1000, 1000)
                // 반복 없음
                val repeat = -1
    
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    vibrator.vibrate(VibrationEffect.createWaveform(vibratePattern, repeat))
                } else {
                    vibrator.vibrate(vibratePattern, repeat)
                }
                Toast.makeText(applicationContext, "진동 패턴", Toast.LENGTH_SHORT).show()
            }
    
            /** 진동 - 취소 */
            binding.tvVibrateCancel.setOnClickListener {
                vibrator.cancel()
                Toast.makeText(applicationContext, "진동 취소", Toast.LENGTH_SHORT).show()
            }
        }
    }

     

     

    *activity_main.xml

    - 레이아웃 구성

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <TextView
            android:id="@+id/tv_vibrate_oneshot"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#F0F0F0"
            android:padding="30dp"
            android:text="Vibrate one shot"
            app:layout_constraintBottom_toTopOf="@+id/tv_vibrate_pattern"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <TextView
            android:id="@+id/tv_vibrate_pattern"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#F0F0F0"
            android:padding="30dp"
            android:text="Vibrate pattern"
            app:layout_constraintBottom_toTopOf="@+id/tv_vibrate_cancel"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tv_vibrate_oneshot" />
    
        <TextView
            android:id="@+id/tv_vibrate_cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#F0F0F0"
            android:padding="30dp"
            android:text="Vibrate cancel"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tv_vibrate_pattern" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>

    [참고자료]

    -https://parkho79.tistory.com/122

     

     

     

     

     

     

    전체소스코드

    [전체 소스코드]
    *Vibrate-kotlin: https://github.com/younminchan/kotlin-study/tree/main/Vibrate_kotlin

     

    GitHub - younminchan/kotlin-study: kotlin 다양한 예제코드

    kotlin 다양한 예제코드. Contribute to younminchan/kotlin-study development by creating an account on GitHub.

    github.com

     

    질문 또는 궁굼한 부분은 댓글을 남겨주세요! 친절하게 답변드리겠습니다!

    응원의 댓글은 저에게 큰 힘이 된답니다! :)

    즐거운 하루되세요!

     

    깃허브 보러 놀러오세요 👇 (맞팔환영)

    https://github.com/younminchan

     

    younminchan - Overview

    안드로이드 2년차 개발자 •⚽️/🎤/🥁/🖥/🏃‍♂️/🚴‍♂️/🤟 TechBlog⬇️ minchanyoun.tistory.com - younminchan

    github.com