Last active
January 17, 2020 06:11
-
-
Save Lavanyagaur22/62c94a7ad37b3be6f8a128a88a3cf31c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.lavanya.androidsensors | |
import android.content.Context | |
import android.graphics.Color | |
import android.hardware.Sensor | |
import android.hardware.Sensor.TYPE_GRAVITY | |
import android.hardware.Sensor.TYPE_PROXIMITY | |
import android.hardware.SensorEvent | |
import android.hardware.SensorEventListener | |
import android.hardware.SensorManager | |
import android.os.Bundle | |
import android.util.Log | |
import android.widget.Toast | |
import androidx.appcompat.app.AppCompatActivity | |
import kotlinx.android.synthetic.main.activity_main.* | |
class MainActivity : AppCompatActivity(), SensorEventListener { | |
private lateinit var sensorManager: SensorManager | |
private lateinit var gravSensor: Sensor | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
val sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager | |
val listOfSensors = sensorManager.getSensorList(Sensor.TYPE_ALL) | |
//To see the details of the sensor | |
listOfSensors.forEach { | |
Log.d("TAG", "Name : " + it.name) | |
Log.d("TAG", "Type : " + it.stringType) | |
... | |
} | |
gravSensor = sensorManager.getDefaultSensor(TYPE_GRAVITY) | |
} | |
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { | |
//This is called whenever the accuracy of the sensor in use changes. | |
//Perform the action. | |
} | |
override fun onSensorChanged(event: SensorEvent?) { | |
//If there is a new sensor data. Perform the action. | |
} | |
//Registering a SensorEventListener | |
override fun onResume() { | |
super.onResume() | |
gravSensor?.also { it -> | |
sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_NORMAL) | |
} | |
} | |
//Unregistering a SensorEventListener | |
override fun onPause() { | |
super.onPause() | |
sensorManager.unregisterListener(this) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment