-
Notifications
You must be signed in to change notification settings - Fork 1
/
sensor
76 lines (62 loc) · 2.1 KB
/
sensor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.mrtechy.gfg_sensor
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 {
// Initialised sensorManager & two variables
// for storing brightness value
private lateinit var sensorManager: SensorManager
private var brightness: Sensor? = null
private lateinit var text: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Set default nightmode
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
// searched our textview id and stored it
text = findViewById(R.id.tv_text)
// setupSensor Called
setUpSensor()
}
// Declared setupSensor function
private fun setUpSensor() {
sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
brightness = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT)
}
// These are two methods from sensorEventListner Interface
override fun onSensorChanged(event: SensorEvent?) {
if (event?.sensor?.type == Sensor.TYPE_LIGHT) {
val light1 = event.values[0]
text.text = "Sensor: $light1\n${brightness(light1)}"
}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
return
}
// Created a function to show messages according to the brightness
private fun brightness(brightness: Float): String {
return when (brightness.toInt()) {
0 -> "Pitch black"
in 1..10 -> "Dark"
in 11..50 -> "Grey"
in 51..5000 -> "Normal"
in 5001..25000 -> "Incredibly bright"
else -> "This light will blind you"
}
}
// This is onResume function of our app
override fun onResume() {
super.onResume()
sensorManager.registerListener(this, brightness, SensorManager.SENSOR_DELAY_NORMAL)
}
// This is onPause function of our app
override fun onPause() {
super.onPause()
sensorManager.unregisterListener(this)
}
}