Step by step Accelerometer examples for android.
Learn programmatic usage of accelerometer in your mobile app.
What is an Accelerometer?
An accelerometer is a tool that measures proper acceleration. Proper acceleration is the acceleration of a body in its own instantaneous rest frame; this is different from coordinate acceleration, which is acceleration in a fixed coordinate system
Majprity of high-end modern smartphones tend to be fitted with an accelerometer. Thus we need to learn how to use it programmatically.
Here are some examples:
1. Simple Accelerometer Example
Practice of accelerometer in android devices, let's move that ball.
Here is the demo project:
Step 1. Our Android Manifest
We will need to look at our AndroidManifest.xml
.
(a). AndroidManifest.xml
Our
AndroidManifest
file.
Here we will add the following permission:
- Our
VIBRATE
permission.
Here is the full Android Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.projects.enzoftware.metalball">
<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=".MetalBall">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 2. Design Layouts
Here are the layouts for this project:
(a). activity_metal_ball.xml
Our
activity_metal_ball
layout.
Inside your /res/layout/
directory create an xml layout file named activity_metal_ball.xml
.
Add these two widgets:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.projects.enzoftware.metalball.MetalBall">
<TextView
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" />
</android.support.constraint.ConstraintLayout>
Step 3. Write Code
Finally we need to write our code as follows:
(a). MetalBall.kt
Our
MetalBall
class.
Create a Kotlin file named MetalBall.kt
.
We will then add imports from android SDK and other packages. Here are some of the imports we will use in this class:
Service
from theandroid.app
package.BluetoothClass
from theandroid.bluetooth
package.Context
from theandroid.content
package.ActivityInfo
from theandroid.content.pm
package.Bitmap
from theandroid.graphics
package.BitmapFactory
from theandroid.graphics
package.Canvas
from theandroid.graphics
package.Point
from theandroid.graphics
package.Sensor
from theandroid.hardware
package.SensorEvent
from theandroid.hardware
package.SensorEventListener
from theandroid.hardware
package.SensorManager
from theandroid.hardware
package.Build
from theandroid.os
package.AppCompatActivity
from theandroid.support.v7.app
package.Bundle
from theandroid.os
package.Vibrator
from theandroid.os
package.*
from theandroid.view
package.
Next create a class that derives from AppCompatActivity
and add its contents as follows:
We will be overriding the following functions:
onCreate(savedInstanceState: Bundle?)
.onAccuracyChanged(sensor: Sensor?, accuracy: Int)
.onSensorChanged(event: SensorEvent?)
.onResume()
.onPause()
.run()
.surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int)
.surfaceDestroyed(holder: SurfaceHolder?)
.surfaceCreated(holder: SurfaceHolder?)
.draw(canvas: Canvas?)
.onDraw(canvas: Canvas?)
.
We will be creating the following methods:
setRunning(parameter)
- This function will take aBoolean
object as a parameter.updateMe(inx : Float , iny : Float)
.
(a). Our setRunning()
function
Write the setRunning()
function as follows:
fun setRunning(run : Boolean){
this.run = run
}
(b). Our updateMe()
function
Write the updateMe()
function as follows:
fun updateMe(inx : Float , iny : Float){
lastGx += inx
lastGy += iny
cx += lastGx
cy += lastGy
if(cx > (Windowwidth - picWidth)){
cx = (Windowwidth - picWidth).toFloat()
lastGx = 0F
if (noBorderX){
vibratorService!!.vibrate(100)
noBorderX = false
}
}
else if(cx < (0)){
cx = 0F
lastGx = 0F
if(noBorderX){
vibratorService!!.vibrate(100)
noBorderX = false
}
}
else{ noBorderX = true }
if (cy > (Windowheight - picHeight)){
cy = (Windowheight - picHeight).toFloat()
lastGy = 0F
if (noBorderY){
vibratorService!!.vibrate(100)
noBorderY = false
}
}
else if(cy < (0)){
cy = 0F
lastGy = 0F
if (noBorderY){
vibratorService!!.vibrate(100)
noBorderY= false
}
}
else{ noBorderY = true }
invalidate()
}
Here is the full code:
package replace_with_your_package_name
import android.app.Service
import android.bluetooth.BluetoothClass
import android.content.Context
import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Point
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Vibrator
import android.view.*
class MetalBall : AppCompatActivity() , SensorEventListener {
private var mSensorManager : SensorManager ?= null
private var mAccelerometer : Sensor ?= null
var ground : GroundView ?= null
override fun onCreate(savedInstanceState: Bundle?) {
requestWindowFeature(Window.FEATURE_NO_TITLE)
super.onCreate(savedInstanceState)
// get reference of the service
mSensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
// focus in accelerometer
mAccelerometer = mSensorManager!!.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
// setup the window
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
View.SYSTEM_UI_FLAG_FULLSCREEN
View.SYSTEM_UI_FLAG_IMMERSIVE
}
// set the view
ground = GroundView(this)
setContentView(ground)
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
override fun onSensorChanged(event: SensorEvent?) {
if (event != null) {
ground!!.updateMe(event.values[1] , event.values[0])
}
}
override fun onResume() {
super.onResume()
mSensorManager!!.registerListener(this,mAccelerometer,
SensorManager.SENSOR_DELAY_GAME)
}
override fun onPause() {
super.onPause()
mSensorManager!!.unregisterListener(this)
}
class DrawThread (surfaceHolder: SurfaceHolder , panel : GroundView) : Thread() {
private var surfaceHolder :SurfaceHolder ?= null
private var panel : GroundView ?= null
private var run = false
init {
this.surfaceHolder = surfaceHolder
this.panel = panel
}
fun setRunning(run : Boolean){
this.run = run
}
override fun run() {
var c: Canvas ?= null
while (run){
c = null
try {
c = surfaceHolder!!.lockCanvas(null)
synchronized(surfaceHolder!!){
panel!!.draw(c)
}
}finally {
if (c!= null){
surfaceHolder!!.unlockCanvasAndPost(c)
}
}
}
}
}
}
class GroundView(context: Context?) : SurfaceView(context), SurfaceHolder.Callback{
// ball coordinates
var cx : Float = 10.toFloat()
var cy : Float = 10.toFloat()
// last position increment
var lastGx : Float = 0.toFloat()
var lastGy : Float = 0.toFloat()
// graphic size of the ball
var picHeight: Int = 0
var picWidth : Int = 0
var icon:Bitmap ?= null
// window size
var Windowwidth : Int = 0
var Windowheight : Int = 0
// is touching the edge ?
var noBorderX = false
var noBorderY = false
var vibratorService : Vibrator ?= null
var thread : MetalBall.DrawThread?= null
init {
holder.addCallback(this)
//create a thread
thread = MetalBall.DrawThread(holder, this)
// get references and sizes of the objects
val display: Display = (getContext().getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
val size:Point = Point()
display.getSize(size)
Windowwidth = size.x
Windowheight = size.y
icon = BitmapFactory.decodeResource(resources,R.drawable.ball)
picHeight = icon!!.height
picWidth = icon!!.width
vibratorService = (getContext().getSystemService(Service.VIBRATOR_SERVICE)) as Vibrator
}
override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
}
override fun surfaceDestroyed(holder: SurfaceHolder?) {
}
override fun surfaceCreated(holder: SurfaceHolder?) {
thread!!.setRunning(true)
thread!!.start()
}
override fun draw(canvas: Canvas?) {
super.draw(canvas)
if (canvas != null){
canvas.drawColor(0xFFAAAAA)
canvas.drawBitmap(icon,cx,cy,null)
}
}
override public fun onDraw(canvas: Canvas?) {
if (canvas != null){
canvas.drawColor(0xFFAAAAA)
canvas.drawBitmap(icon,cx,cy,null)
}
}
fun updateMe(inx : Float , iny : Float){
lastGx += inx
lastGy += iny
cx += lastGx
cy += lastGy
if(cx > (Windowwidth - picWidth)){
cx = (Windowwidth - picWidth).toFloat()
lastGx = 0F
if (noBorderX){
vibratorService!!.vibrate(100)
noBorderX = false
}
}
else if(cx < (0)){
cx = 0F
lastGx = 0F
if(noBorderX){
vibratorService!!.vibrate(100)
noBorderX = false
}
}
else{ noBorderX = true }
if (cy > (Windowheight - picHeight)){
cy = (Windowheight - picHeight).toFloat()
lastGy = 0F
if (noBorderY){
vibratorService!!.vibrate(100)
noBorderY = false
}
}
else if(cy < (0)){
cy = 0F
lastGy = 0F
if (noBorderY){
vibratorService!!.vibrate(100)
noBorderY= false
}
}
else{ noBorderY = true }
invalidate()
}
}
Reference
Download the code below:
No. | Link |
---|---|
1. | Download Full Code |
2. | Read more here. |
3. | Follow code author here. |
2. Accelerometer Experimentation
Experimentation with how to use the accelerometer to make cool effects on Android in Kotlin.
Below is a full android sample to demonstrate Accelerometer concept.
Step 1. Design Layouts
(a). activity_main.xml
Our
activity_main
layout.
Design your XML layout using the following 2 UI widgets and ViewGroups:
<?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"
android:background="#212121"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_square"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:background="#EF5350"
android:gravity="center"
android:text="Hello"
android:textColor="@color/white"
android:textSize="20sp" />
</RelativeLayout>
Step 2. Write Code
Finally we need to write our code as follows:
(a). MainActivity.kt
Our
MainActivity
class.
Create a Kotlin file named MainActivity.kt
.
We will then add imports from android SDK and other packages. Here are some of the imports we will use in this class:
Color
from theandroid.graphics
package.Sensor
from theandroid.hardware
package.SensorEvent
from theandroid.hardware
package.SensorEventListener
from theandroid.hardware
package.SensorManager
from theandroid.hardware
package.AppCompatActivity
from theandroidx.appcompat.app
package.Bundle
from theandroid.os
package.TextView
from theandroid.widget
package.AppCompatDelegate
from theandroidx.appcompat.app
package.
Next create a class that derives from AppCompatActivity
and add its contents as follows:
We will be overriding the following functions:
onCreate(savedInstanceState: Bundle?)
.onSensorChanged(event: SensorEvent?)
.onAccuracyChanged(sensor: Sensor?, accuracy: Int)
.onDestroy()
.
We will be creating the following methods:
setUpSensorStuff()
.
(a). Our setUpSensorStuff()
function
WesetUpSensorStuff()
as follows:
private fun setUpSensorStuff() {
// Create the sensor manager
sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
// Specify the sensor you want to listen to
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)?.also { accelerometer ->
sensorManager.registerListener(
this,
accelerometer,
SensorManager.SENSOR_DELAY_FASTEST,
SensorManager.SENSOR_DELAY_FASTEST
)
}
}
Here is the full code:
package replace_with_your_package_name
import android.graphics.Color
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.TextView
import androidx.appcompat.app.AppCompatDelegate
class MainActivity : AppCompatActivity(), SensorEventListener {
private lateinit var sensorManager: SensorManager
private lateinit var square: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Keeps phone in light mode
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
square = findViewById(R.id.tv_square)
setUpSensorStuff()
}
private fun setUpSensorStuff() {
// Create the sensor manager
sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
// Specify the sensor you want to listen to
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)?.also { accelerometer ->
sensorManager.registerListener(
this,
accelerometer,
SensorManager.SENSOR_DELAY_FASTEST,
SensorManager.SENSOR_DELAY_FASTEST
)
}
}
override fun onSensorChanged(event: SensorEvent?) {
// Checks for the sensor we have registered
if (event?.sensor?.type == Sensor.TYPE_ACCELEROMETER) {
//Log.d("Main", "onSensorChanged: sides ${event.values[0]} front/back ${event.values[1]} ")
// Sides = Tilting phone left(10) and right(-10)
val sides = event.values[0]
// Up/Down = Tilting phone up(10), flat (0), upside-down(-10)
val upDown = event.values[1]
square.apply {
rotationX = upDown * 3f
rotationY = sides * 3f
rotation = -sides
translationX = sides * -10
translationY = upDown * 10
}
// Changes the colour of the square if it's completely flat
val color = if (upDown.toInt() == 0 && sides.toInt() == 0) Color.GREEN else Color.RED
square.setBackgroundColor(color)
square.text = "up/down ${upDown.toInt()}nleft/right ${sides.toInt()}"
}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
return
}
override fun onDestroy() {
sensorManager.unregisterListener(this)
super.onDestroy()
}
}
Reference
Download the code below:
No. | Link |
---|---|
1. | Download Full Code |
2. | Read more here. |
3. | Follow code author here. |