Skip to content

Instantly share code, notes, and snippets.

@thinhbuzz
Created June 19, 2022 15:31
Show Gist options
  • Save thinhbuzz/c474e2b8e8ec0aca86f56a257e29ceb3 to your computer and use it in GitHub Desktop.
Save thinhbuzz/c474e2b8e8ec0aca86f56a257e29ceb3 to your computer and use it in GitHub Desktop.
package net.pgtools.auto
import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.IBinder
import android.os.PowerManager
import com.google.firebase.crashlytics.ktx.crashlytics
import com.google.firebase.ktx.Firebase
class AutoService : Service(), SensorEventListener {
private var proximitySensor: Sensor? = null
private var sm: SensorManager? = null
private var powerManager: PowerManager? = null
private var lock: PowerManager.WakeLock? = null
override fun onBind(intent: Intent): IBinder? {
return null
}
@SuppressLint("WakelockTimeout")
override fun onSensorChanged(event: SensorEvent?) {
if (event == null || event.sensor.type != Sensor.TYPE_PROXIMITY || proximitySensor == null || lock == null) {
return
}
if (event.values[0] < proximitySensor!!.maximumRange) {
if (!lock!!.isHeld) {
lock!!.acquire()
}
} else {
if (lock!!.isHeld) {
lock!!.release()
}
}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
override fun onCreate() {
super.onCreate()
handleProximitySensor()
}
private fun handleProximitySensor() {
try {
sm = getSystemService(SENSOR_SERVICE) as SensorManager
proximitySensor = sm!!.getDefaultSensor(Sensor.TYPE_PROXIMITY)
sm!!.registerListener(this, proximitySensor, SensorManager.SENSOR_DELAY_NORMAL)
powerManager = getSystemService(POWER_SERVICE) as PowerManager
lock = powerManager!!.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "pgtools:pac")
} catch (e: Exception) {
Firebase.crashlytics.recordException(e)
e.printStackTrace()
}
}
override fun onDestroy() {
super.onDestroy()
if (lock?.isHeld == true) {
lock!!.release()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment