AndroidAPS/app/src/main/java/info/nightscout/androidaps/MainApp.kt

234 lines
11 KiB
Kotlin
Raw Normal View History

package info.nightscout.androidaps
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.os.Build
2022-04-03 00:54:32 +02:00
import android.os.Handler
import android.os.HandlerThread
import androidx.lifecycle.ProcessLifecycleOwner
2022-03-30 20:13:38 +02:00
import androidx.work.Data
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
2021-10-10 18:05:55 +02:00
import com.uber.rxdogtag.RxDogTag
import dagger.android.AndroidInjector
import dagger.android.DaggerApplication
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TherapyEvent
2021-04-10 11:35:38 +02:00
import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction
import info.nightscout.androidaps.database.transactions.VersionChangeTransaction
import info.nightscout.androidaps.db.CompatDBHelper
2022-01-06 17:45:00 +01:00
import info.nightscout.androidaps.di.DaggerAppComponent
2021-10-20 22:54:32 +02:00
import info.nightscout.androidaps.di.StaticInjector
2021-04-14 18:42:12 +02:00
import info.nightscout.androidaps.interfaces.Config
2021-05-29 23:38:19 +02:00
import info.nightscout.androidaps.interfaces.ConfigBuilder
import info.nightscout.androidaps.interfaces.PluginBase
2022-05-19 16:56:48 +02:00
import info.nightscout.androidaps.interfaces.ResourceHelper
2021-04-10 11:35:38 +02:00
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.configBuilder.PluginStore
import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils
2021-11-28 18:20:52 +01:00
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore
2022-03-18 16:04:08 +01:00
import info.nightscout.androidaps.plugins.general.themes.ThemeSwitcherPlugin
2022-04-11 14:25:00 +02:00
import info.nightscout.androidaps.receivers.BTReceiver
import info.nightscout.androidaps.receivers.ChargingStateReceiver
import info.nightscout.androidaps.receivers.KeepAliveWorker
import info.nightscout.androidaps.receivers.NetworkChangeReceiver
import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver
2021-10-26 13:41:48 +02:00
import info.nightscout.androidaps.services.AlarmSoundServiceHelper
import info.nightscout.androidaps.utils.ActivityMonitor
import info.nightscout.androidaps.utils.DateUtil
2022-03-30 20:13:38 +02:00
import info.nightscout.androidaps.utils.LocalAlertUtils
import info.nightscout.androidaps.utils.ProcessLifecycleListener
2021-11-28 18:20:52 +01:00
import info.nightscout.androidaps.utils.buildHelper.BuildHelper
2021-10-23 21:08:31 +02:00
import info.nightscout.androidaps.utils.locale.LocaleHelper
2022-04-06 00:23:01 +02:00
import info.nightscout.androidaps.widget.updateWidget
2022-03-29 15:55:51 +02:00
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
2021-12-10 12:17:03 +01:00
import info.nightscout.shared.sharedPreferences.SP
2022-02-10 19:11:58 +01:00
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.exceptions.UndeliverableException
import io.reactivex.rxjava3.kotlin.plusAssign
import io.reactivex.rxjava3.plugins.RxJavaPlugins
2021-10-20 22:54:32 +02:00
import java.io.IOException
import java.net.SocketException
2022-03-30 20:13:38 +02:00
import java.util.concurrent.TimeUnit
import javax.inject.Inject
2022-05-19 16:56:48 +02:00
import javax.inject.Provider
class MainApp : DaggerApplication() {
private val disposable = CompositeDisposable()
@Inject lateinit var pluginStore: PluginStore
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var activityMonitor: ActivityMonitor
@Inject lateinit var versionCheckersUtils: VersionCheckerUtils
@Inject lateinit var sp: SP
@Inject lateinit var config: Config
2021-11-28 18:20:52 +01:00
@Inject lateinit var buildHelper: BuildHelper
2021-04-13 23:27:55 +02:00
@Inject lateinit var configBuilder: ConfigBuilder
@Inject lateinit var plugins: List<@JvmSuppressWildcards PluginBase>
@Inject lateinit var compatDBHelper: CompatDBHelper
@Inject lateinit var repository: AppRepository
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var staticInjector: StaticInjector// TODO avoid , here fake only to initialize
2021-04-10 11:35:38 +02:00
@Inject lateinit var uel: UserEntryLogger
2021-10-26 13:41:48 +02:00
@Inject lateinit var alarmSoundServiceHelper: AlarmSoundServiceHelper
2021-11-28 18:20:52 +01:00
@Inject lateinit var notificationStore: NotificationStore
@Inject lateinit var processLifecycleListener: ProcessLifecycleListener
2022-03-18 16:04:08 +01:00
@Inject lateinit var profileSwitchPlugin: ThemeSwitcherPlugin
2022-03-30 20:13:38 +02:00
@Inject lateinit var localAlertUtils: LocalAlertUtils
2022-05-19 16:56:48 +02:00
@Inject lateinit var rh: Provider<ResourceHelper>
2022-04-03 00:54:32 +02:00
private var handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private lateinit var refreshWidget: Runnable
override fun onCreate() {
super.onCreate()
aapsLogger.debug("onCreate")
2021-10-10 18:05:55 +02:00
RxDogTag.install()
2021-10-20 22:54:32 +02:00
setRxErrorHandler()
2021-10-23 21:08:31 +02:00
LocaleHelper.update(this)
ProcessLifecycleOwner.get().lifecycle.addObserver(processLifecycleListener)
var gitRemote: String? = BuildConfig.REMOTE
var commitHash: String? = BuildConfig.HEAD
if (gitRemote?.contains("NoGitSystemAvailable") == true) {
gitRemote = null
commitHash = null
}
disposable += compatDBHelper.dbChangeDisposable()
registerActivityLifecycleCallbacks(activityMonitor)
2022-03-18 16:04:08 +01:00
profileSwitchPlugin.setThemeMode()
aapsLogger.debug("Version: " + BuildConfig.VERSION_NAME)
aapsLogger.debug("BuildVersion: " + BuildConfig.BUILDVERSION)
aapsLogger.debug("Remote: " + BuildConfig.REMOTE)
registerLocalBroadcastReceiver()
2021-11-28 18:20:52 +01:00
// trigger here to see the new version on app start after an update
versionCheckersUtils.triggerCheckVersion()
// Register all tabs in app here
pluginStore.plugins = plugins
2021-04-13 23:27:55 +02:00
configBuilder.initialize()
2022-03-30 20:13:38 +02:00
2022-05-19 16:56:48 +02:00
// delayed actions to make rh context updated for translations
handler.postDelayed(
{
// check if identification is set
if (buildHelper.isDev() && sp.getStringOrNull(R.string.key_email_for_crash_report, null).isNullOrBlank())
notificationStore.add(Notification(Notification.IDENTIFICATION_NOT_SET, rh.get().gs(R.string.identification_not_set), Notification.INFO))
// log version
disposable += repository.runTransaction(VersionChangeTransaction(BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE, gitRemote, commitHash)).subscribe()
// log app start
if (sp.getBoolean(R.string.key_ns_logappstartedevent, config.APS))
disposable += repository
.runTransaction(
InsertIfNewByTimestampTherapyEventTransaction(
timestamp = dateUtil.now(),
type = TherapyEvent.Type.NOTE,
note = rh.get().gs(info.nightscout.androidaps.core.R.string.androidaps_start) + " - " + Build.MANUFACTURER + " " + Build.MODEL,
glucoseUnit = TherapyEvent.GlucoseUnit.MGDL
)
)
.subscribe()
}, 10000
)
2022-03-30 20:13:38 +02:00
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
"KeepAlive",
ExistingPeriodicWorkPolicy.REPLACE,
PeriodicWorkRequest.Builder(KeepAliveWorker::class.java, 15, TimeUnit.MINUTES)
.setInputData(Data.Builder().putString("schedule", "KeepAlive").build())
.setInitialDelay(5, TimeUnit.SECONDS)
.build()
)
localAlertUtils.shortenSnoozeInterval()
localAlertUtils.preSnoozeAlarms()
doMigrations()
2021-04-10 11:35:38 +02:00
uel.log(UserEntry.Action.START_AAPS, UserEntry.Sources.Aaps)
2022-04-03 00:54:32 +02:00
// schedule widget update
refreshWidget = Runnable {
handler.postDelayed(refreshWidget, 60000)
updateWidget(this)
}
handler.postDelayed(refreshWidget, 60000)
}
2021-10-20 22:54:32 +02:00
private fun setRxErrorHandler() {
RxJavaPlugins.setErrorHandler { t: Throwable ->
var e = t
if (e is UndeliverableException) {
e = e.cause!!
}
if (e is IOException || e is SocketException) {
// fine, irrelevant network problem or API that throws on cancellation
return@setErrorHandler
}
if (e is InterruptedException) {
// fine, some blocking code was interrupted by a dispose call
return@setErrorHandler
}
if (e is NullPointerException || e is IllegalArgumentException) {
// that's likely a bug in the application
Thread.currentThread().uncaughtExceptionHandler?.uncaughtException(Thread.currentThread(), e)
return@setErrorHandler
}
if (e is IllegalStateException) {
// that's a bug in RxJava or in a custom operator
Thread.currentThread().uncaughtExceptionHandler?.uncaughtException(Thread.currentThread(), e)
return@setErrorHandler
}
aapsLogger.warn(LTag.CORE, "Undeliverable exception received, not sure what to do", e)
}
}
private fun doMigrations() {
// set values for different builds
if (!sp.contains(R.string.key_ns_alarms)) sp.putBoolean(R.string.key_ns_alarms, config.NSCLIENT)
if (!sp.contains(R.string.key_ns_announcements)) sp.putBoolean(R.string.key_ns_announcements, config.NSCLIENT)
if (!sp.contains(R.string.key_language)) sp.putString(R.string.key_language, "default")
}
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerAppComponent
.builder()
.application(this)
.build()
}
private fun registerLocalBroadcastReceiver() {
var filter = IntentFilter()
filter.addAction(Intent.ACTION_TIME_CHANGED)
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED)
registerReceiver(TimeDateOrTZChangeReceiver(), filter)
filter = IntentFilter()
@Suppress("DEPRECATION")
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
registerReceiver(NetworkChangeReceiver(), filter)
filter = IntentFilter()
filter.addAction(Intent.ACTION_POWER_CONNECTED)
filter.addAction(Intent.ACTION_POWER_DISCONNECTED)
filter.addAction(Intent.ACTION_BATTERY_CHANGED)
registerReceiver(ChargingStateReceiver(), filter)
filter = IntentFilter()
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
registerReceiver(BTReceiver(), filter)
}
override fun onTerminate() {
aapsLogger.debug(LTag.CORE, "onTerminate")
unregisterActivityLifecycleCallbacks(activityMonitor)
2021-10-26 13:41:48 +02:00
alarmSoundServiceHelper.stopService(this)
super.onTerminate()
}
2021-10-10 18:05:55 +02:00
}