Accelerometer Sensors in Android devices are used to detect the orientation of the device. This helps the application change the orientation when tilted when set to auto-rotate. Moreover, multiple applications use data from accelerometer sensors for performing various actions. For example, a shake can be used to pause a playing video on the device. So in this article, we will show you how you could detect shake movement in Android. Follow the below steps once the IDE is ready.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. No changes are required in this file, so keep it untouched.
<? xml version = "1.0" encoding = "utf-8" ?>
< androidx.constraintlayout.widget.ConstraintLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< TextView
android:id = "@+id/text_view_1"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Hello World!"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintLeft_toLeftOf = "parent"
app:layout_constraintRight_toRightOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</ androidx.constraintlayout.widget.ConstraintLayout >
|
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
package org.geeksforgeeks.detectphysicalshake
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import java.util.*
import kotlin.math.sqrt
class MainActivity : AppCompatActivity() {
// Declaring sensorManager
// and acceleration constants
private var sensorManager: SensorManager? = null
private var acceleration = 0f
private var currentAcceleration = 0f
private var lastAcceleration = 0f
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Getting the Sensor Manager instance
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
Objects.requireNonNull(sensorManager)!!
.registerListener(sensorListener, sensorManager!!
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL)
acceleration = 10f
currentAcceleration = SensorManager.GRAVITY_EARTH
lastAcceleration = SensorManager.GRAVITY_EARTH
}
private val sensorListener: SensorEventListener = object : SensorEventListener {
override fun onSensorChanged(event: SensorEvent) {
// Fetching x,y,z values
val x = event.values[ 0 ]
val y = event.values[ 1 ]
val z = event.values[ 2 ]
lastAcceleration = currentAcceleration
// Getting current accelerations
// with the help of fetched x,y,z values
currentAcceleration = sqrt((x * x + y * y + z * z).toDouble()).toFloat()
val delta: Float = currentAcceleration - lastAcceleration
acceleration = acceleration * 0 .9f + delta
// Display a Toast message if
// acceleration value is over 12
if (acceleration > 12 ) {
Toast.makeText(applicationContext, "Shake event detected" , Toast.LENGTH_SHORT).show()
}
}
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
}
override fun onResume() {
sensorManager?.registerListener(sensorListener, sensorManager!!.getDefaultSensor(
Sensor .TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL
)
super .onResume()
}
override fun onPause() {
sensorManager!!.unregisterListener(sensorListener)
super .onPause()
}
} |
Output:
You can observe that when you shake the device, a Toast would be displayed.