Skip to content

Instantly share code, notes, and snippets.

@RobertApikyan
Created October 26, 2020 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobertApikyan/9f63417534a59b69741f6a8cf199c05a to your computer and use it in GitHub Desktop.
Save RobertApikyan/9f63417534a59b69741f6a8cf199c05a to your computer and use it in GitHub Desktop.
package com.hfh.wellbe.smartwatch.receivers
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.wifi.WifiManager
import android.os.PowerManager
import android.os.SystemClock
import com.hfh.wellbe.smartwatch.managers.Logger
import com.hfh.wellbe.smartwatch.managers.Managers
import com.hfh.wellbe.smartwatch.utils.delay
import com.hfh.wellbe.smartwatch.utils.tryTo
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.*
import java.util.concurrent.TimeUnit
class ReportDeviceHealthReceiver : BroadcastReceiver() {
private lateinit var context: Context
private val wifiLock by lazy {
(context.getSystemService(Context.WIFI_SERVICE) as WifiManager)
.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, WIFI_WAKE_LOCK)
}
override fun onReceive(context: Context, intent: Intent) {
this.context = context
if (intent.action == ACTION) {
acquireWakeLock()
delay(15000){
Managers.getDeviceSettingsManager().setWifiEnabled(true).onComplete {
Managers.getDeviceSettingsManager().reportDeviceHealth()
.onSuccess { healthReport ->
Logger.log(TAG, "SUCCESS\n${Date()}\nhealthReport= $healthReport")
}
.onFailure { throwable ->
Logger.log(TAG, "FAILURE\n${Date()}\nerror = ${throwable?.message}")
}.onComplete {
releaseWakeLock()
scheduleReportDeviceHealthReceiver(context)
}
}
}
}
}
private fun acquireWakeLock() {
tryTo {
if (!wifiLock.isHeld) {
wifiLock.acquire()
}
}
}
private fun releaseWakeLock() {
tryTo {
if (wifiLock.isHeld) {
wifiLock.release()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment