Vibrate Phone | Android Studio | Kotlin
How to vibrate phone programmatically for a specific time?
You can easily implement the phone vibrate programmatically using Android Vibrator API. In this example, we will vibrate the phone for 1000 microseconds i.e. 1 second by clicking a button you can change the duration according to your requirements.
Step 1: Create a new project OR open an existing project
Step 2: Code
Open AndroidManifest and add VIBRATE permission.
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.blogspot.atifsoftwares.vibratephone">
<!--VIBRATE permission-->
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Click vibrate button below to start vibrating your phone."
android:textAlignment="center"
android:textColor="#000"
android:textSize="20sp" />
<Button
android:id="@+id/vibrateBtn"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:minWidth="150dp"
android:text="Vibrate" />
</RelativeLayout>
MainActivity.kt
package com.blogspot.atifsoftwares.vibratephone
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//init Android Vibrator API
val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
//handle button click, vibrate phone for 1000 microsecs (1 second)
vibrateBtn.setOnClickListener {
if (Build.VERSION.SDK_INT >= 26) {
vibrator.vibrate(VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
vibrator.vibrate(1000)
}
}
}
}
Comments
Post a Comment