diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index abe1b51c..6c64fa2b 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -51,26 +51,38 @@
-
-
-
-
-
-
-
+
-
-
-
+
+
+
+
+ android:theme="@style/AppTheme"
+ android:usesCleartextTraffic="true">
@@ -162,6 +174,10 @@
+
+
Unit = periodic_run_app_logic
- val periodic_run_app_logic: () -> Unit = {
- // printd("run_all_app_logic - ThreadHandler")
- run_all_app_logic()
- // in the scope of this closure "periodic_run_app_logic" doesn't exist, we need to access it, not referency it.
- background_handler.postDelayed(get_periodic_run_app_logic(), THREADHANDLER_PERIODICITY)
- }
-
- fun doSetup() {
- // Accelerometer, gyro, power state, and wifi don't need permissions or they are checked in
- // the broadcastreceiver logic
- startPowerStateListener()
- gpsListener = GPSListener(applicationContext)
- WifiListener.initialize(applicationContext)
-
- if (PersistentData.getAccelerometerEnabled())
- accelerometerListener = AccelerometerListener(applicationContext)
- if (PersistentData.getGyroscopeEnabled())
- gyroscopeListener = GyroscopeListener(applicationContext)
-
- // Bluetooth, wifi, gps, calls, and texts need permissions
- if (confirmBluetooth(applicationContext))
- startBluetooth()
-
- if (confirmTexts(applicationContext)) {
- startSmsSentLogger()
- startMmsSentLogger()
- } else if (PersistentData.getTextsEnabled()) {
- sendBroadcast(Timer.checkForSMSEnabledIntent)
- }
- if (confirmCallLogging(applicationContext))
- startCallLogger()
- else if (PersistentData.getCallLoggingEnabled())
- sendBroadcast(Timer.checkForCallsEnabledIntent)
-
- // Only do the following if the device is registered
- if (PersistentData.getIsRegistered()) {
- DeviceInfo.initialize(applicationContext) // if at registration this has already been initialized. (we don't care.)
- startTimers()
- }
- }
-
- private fun createNotificationChannel() {
- // setup the notification channel so the service can run in the foreground
- val chan = NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT)
- chan.lightColor = Color.BLUE
- chan.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
- chan.setSound(null, null)
- val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
- manager.createNotificationChannel(chan)
- }
-
- /*#############################################################################
- ######################### Starters #######################
- #############################################################################*/
-
- /** Initializes the Bluetooth listener
- * Bluetooth has several checks to make sure that it actually exists on the device with the
- * capabilities we need. Checking for Bluetooth LE is necessary because it is an optional
- * extension to Bluetooth 4.0. */
- fun startBluetooth() {
- // Note: the Bluetooth listener is a BroadcastReceiver, which means it must have a 0-argument
- // constructor in order for android to instantiate it on broadcast receipts. The following
- // check must be made, but it requires a Context that we cannot pass into the
- // BluetoothListener, so we do the check in the BackgroundService.
- if (applicationContext.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
- && PersistentData.getBluetoothEnabled()) {
- bluetoothListener = BluetoothListener()
- if (bluetoothListener!!.isBluetoothEnabled) {
- val intent_filter = IntentFilter("android.bluetooth.adapter.action.STATE_CHANGED")
- registerReceiver(bluetoothListener, intent_filter)
- } else {
- // TODO: Track down why this error occurs, cleanup. The above check should be for
- // the (new) doesBluetoothCapabilityExist function instead of isBluetoothEnabled
- Log.e("Main Service", BLLUETOOTH_MESSAGE_1)
- TextFileManager.writeDebugLogStatement(BLLUETOOTH_MESSAGE_1)
- }
- } else {
- if (PersistentData.getBluetoothEnabled()) {
- TextFileManager.writeDebugLogStatement(BLLUETOOTH_MESSAGE_2)
- Log.w("MainS bluetooth init", BLLUETOOTH_MESSAGE_2)
- }
- bluetoothListener = null
- }
- }
-
- /** Initializes the sms logger. */
- fun startSmsSentLogger() {
- val smsSentLogger = SmsSentLogger(Handler(), applicationContext)
- this.contentResolver.registerContentObserver(
- Uri.parse("content://sms/"), true, smsSentLogger)
- }
-
- fun startMmsSentLogger() {
- val mmsMonitor = MMSSentLogger(Handler(), applicationContext)
- this.contentResolver.registerContentObserver(
- Uri.parse("content://mms/"), true, mmsMonitor)
- }
-
- /** Initializes the call logger. */
- private fun startCallLogger() {
- val callLogger = CallLogger(Handler(), applicationContext)
- this.contentResolver.registerContentObserver(
- Uri.parse("content://call_log/calls/"), true, callLogger)
- }
-
- /** Initializes the PowerStateListener.
- * The PowerStateListener requires the ACTION_SCREEN_OFF and ACTION_SCREEN_ON intents be
- * registered programatically. They do not work if registered in the app's manifest. Same for
- * the ACTION_POWER_SAVE_MODE_CHANGED and ACTION_DEVICE_IDLE_MODE_CHANGED filters, though they
- * are for monitoring deeper power state changes in 5.0 and 6.0, respectively. */
- private fun startPowerStateListener() {
- if (powerStateListener == null) {
- val filter = IntentFilter()
- filter.addAction(Intent.ACTION_SCREEN_ON)
- filter.addAction(Intent.ACTION_SCREEN_OFF)
- if (Build.VERSION.SDK_INT >= 21)
- filter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)
- if (Build.VERSION.SDK_INT >= 23)
- filter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED)
- powerStateListener = PowerStateListener()
- registerReceiver(powerStateListener, filter)
- PowerStateListener.start(applicationContext)
- }
- }
-
- /** Gets, sets, and pushes the FCM token to the backend. */
- fun initializeFireBaseIDToken() {
- // Set up the oncomplete listener for the FCM getter code, which in turn sets up a thread
- // that will wait until the participant is registered to actually push it off to the server.
- val fcm_closure = OnCompleteListener { task: Task ->
- // If the task failed, log the error and return, we will resend in the firebase
- // token-changed code, or the FCM_TIMER periodic event.
- if (!task.isSuccessful) {
- Log.e("FCM", FCM_ERROR_MESSAGE, task.exception)
- TextFileManager.writeDebugLogStatement("$FCM_ERROR_MESSAGE(1)")
- return@OnCompleteListener
- }
-
- // Get new Instance ID token - literally can't access task.result in blocker_closure ...?!
- val taskResult = task.result
- if (taskResult == null) {
- TextFileManager.writeDebugLogStatement("$FCM_ERROR_MESSAGE(2)")
- return@OnCompleteListener
- }
-
- // We need to wait until the participant is registered to send the fcm token.
- // (This is a Runnable because we need to return early in an error case with @Runnable)
- val blocker_closure = Runnable {
- while (!PersistentData.getIsRegistered()) {
- try {
- Thread.sleep(1000)
- } catch (ignored: InterruptedException) {
- TextFileManager.writeDebugLogStatement("$FCM_ERROR_MESSAGE(3)")
- return@Runnable
- }
- }
- PersistentData.setFCMInstanceID(taskResult.token)
- PostRequest.sendFCMInstanceID(taskResult.token)
- }
-
- // kick off the blocker thread
- Thread(blocker_closure, "fcm_blocker_thread").start()
- }
-
- // setup oncomplete listener
- FirebaseInstanceId.getInstance().instanceId.addOnCompleteListener(fcm_closure)
- }
-
- /*#############################################################################
- #################### Timer Logic #######################
- #############################################################################*/
-
- fun startTimers() {
- Log.i("BackgroundService", "running startTimer logic.")
- // printd("run_all_app_logic - startTimers")
- run_all_app_logic()
-
- // if Bluetooth recording is enabled and there is no scheduled next-bluetooth-enable event,
- // set up the next Bluetooth-on alarm. (Bluetooth needs to run at absolute points in time,
- // it should not be started if a scheduled event is missed.)
- if (PersistentData.getBluetoothEnabled()) {
- if (confirmBluetooth(applicationContext) && !timer!!.alarmIsSet(Timer.bluetoothOnIntent))
- timer!!.setupExactSingleAbsoluteTimeAlarm(
- PersistentData.getBluetoothTotalDuration(),
- PersistentData.getBluetoothGlobalOffset(),
- Timer.bluetoothOnIntent
- )
- }
-
- // this is a repeating alarm that ensures the service is running, it starts the service if it isn't.
- // Periodicity is FOREGROUND_SERVICE_RESTART_PERIODICITY.
- // This is a special intent, it has a construction that targets the MainService's onStartCommand method.
- val alarmService = applicationContext.getSystemService(ALARM_SERVICE) as AlarmManager
- val restartServiceIntent = Intent(applicationContext, MainService::class.java)
- restartServiceIntent.setPackage(packageName)
- val flags = pending_intent_flag_fix(PendingIntent.FLAG_UPDATE_CURRENT)
- // no clue what this requestcode means, it is 0 on normal pending intents
- val repeatingRestartServicePendingIntent = PendingIntent.getService(
- applicationContext, 1, restartServiceIntent, flags
- )
- alarmService.setRepeating(
- AlarmManager.RTC_WAKEUP,
- System.currentTimeMillis() + FOREGROUND_SERVICE_RESTART_PERIODICITY,
- FOREGROUND_SERVICE_RESTART_PERIODICITY,
- repeatingRestartServicePendingIntent
- )
- }
-
- /**The timerReceiver is an Android BroadcastReceiver that listens for our timer events to trigger,
- * and then runs the appropriate code for that trigger.
- * Note: every condition has a return statement at the end; this is because the trigger survey
- * notification action requires a fairly expensive dive into PersistantData JSON unpacking. */
- private val timerReceiver: BroadcastReceiver = object : BroadcastReceiver() {
- override fun onReceive(applicationContext: Context, intent: Intent?) {
- Log.e("BackgroundService", "Received broadcast: $intent")
- TextFileManager.writeDebugLogStatement("Received Broadcast: " + intent.toString())
-
- if (intent == null)
- return
-
- val broadcastAction = intent.action
- // printd("run_all_app_logic - timerReceiver")
- run_all_app_logic()
-
- /* Bluetooth timers are unlike GPS and Accelerometer because it uses an
- * absolute-point-in-time as a trigger, and therefore we don't need to store
- * most-recent-timer state. The Bluetooth-on action sets the corresponding Bluetooth-off
- * timer, the Bluetooth-off action sets the next Bluetooth-on timer.*/
- if (broadcastAction == applicationContext.getString(R.string.turn_bluetooth_on)) {
- printe("Bluetooth on timer triggered")
- if (!PersistentData.getBluetoothEnabled()) // return, don't set another alarm
- return
-
- if (checkBluetoothPermissions(applicationContext)) {
- if (bluetoothListener != null) bluetoothListener!!.enableBLEScan()
- } else {
- TextFileManager.writeDebugLogStatement("user has not provided permission for Bluetooth.")
- }
- timer!!.setupExactSingleAlarm(PersistentData.getBluetoothOnDuration(), Timer.bluetoothOffIntent)
- return
- }
-
- if (broadcastAction == applicationContext.getString(R.string.turn_bluetooth_off)) {
- printe("Bluetooth off timer triggered")
- if (checkBluetoothPermissions(applicationContext) && bluetoothListener != null) {
- bluetoothListener!!.disableBLEScan()
- }
- timer!!.setupExactSingleAbsoluteTimeAlarm(
- PersistentData.getBluetoothTotalDuration(),
- PersistentData.getBluetoothGlobalOffset(),
- Timer.bluetoothOnIntent
- )
- return
- }
-
- // I don't know if we pull this one out
- // Signs out the user. (does not set up a timer, that is handled in activity and sign-in logic)
- if (broadcastAction == applicationContext.getString(R.string.signout_intent)) {
- // FIXME: does this need to run on the main thread in do_signout_check?
- PersistentData.logout()
- val loginPage = Intent(applicationContext, LoginActivity::class.java) // yup that is still java
- loginPage.flags = Intent.FLAG_ACTIVITY_NEW_TASK
- applicationContext.startActivity(loginPage)
- return
- }
-
- // leave the SMS/MMS/calls logic as-is, it is like this to ensure they are never
- // enabled until the particiant presses the accept button.
- if (broadcastAction == applicationContext.getString(R.string.check_for_sms_enabled)) {
- if (confirmTexts(applicationContext)) {
- startSmsSentLogger()
- startMmsSentLogger()
- } else if (PersistentData.getTextsEnabled())
- timer!!.setupExactSingleAlarm(30000L, Timer.checkForSMSEnabledIntent)
- }
- // logic for the call (metadata) logger
- if (broadcastAction == applicationContext.getString(R.string.check_for_call_log_enabled)) {
- if (confirmCallLogging(applicationContext)) {
- startCallLogger()
- } else if (PersistentData.getCallLoggingEnabled())
- timer!!.setupExactSingleAlarm(30000L, Timer.checkForCallsEnabledIntent)
- }
-
-
- // This code has been removed, the app now explicitly checks app state, and the call
- // to send this particular broadcast is no longer used. We will retain this for now
- // (June 2024) in case we had a real good reason for retaining this pattern now that
- // survey state checking.
- // checks if the action is the id of a survey (expensive), if so pop up the notification
- // for that survey, schedule the next alarm.
- // if (PersistentData.getSurveyIds().contains(broadcastAction)) {
- // // Log.i("MAIN SERVICE", "new notification: " + broadcastAction);
- // displaySurveyNotification(applicationContext, broadcastAction!!)
- // SurveyScheduler.scheduleSurvey(broadcastAction)
- // return
- // }
-
- // these are special actions that will only run if the app device is in debug mode.
- if (broadcastAction == "crashBeiwe" && BuildConfig.APP_IS_BETA) {
- throw NullPointerException("beeeeeoooop.")
- }
- if (broadcastAction == "enterANR" && BuildConfig.APP_IS_BETA) {
- try {
- Thread.sleep(100000)
- } catch (ie: InterruptedException) {
- ie.printStackTrace()
- }
- }
- }
- }
-
- /*##############################################################################
- ########################## Application State Logic #############################
- ##############################################################################*/
-
- // TODO: if we make this use rtc time that will solve time-reset issues. Could also run a sanity check.
- // TODO: test default (should be zero? out of PersistentData) cases.
- // TODO: is there an advantage to sticking the callables onto a queue that is then consumed? leaning no.
-
- /* Abstract function, checks the time, runs the action, sets the next time. */
- fun do_an_event_session_check(
- now: Long,
- identifier_string: String,
- periodicity_in_milliseconds: Long,
- do_action: () -> Unit,
- ) {
- // val t1 = System.currentTimeMillis()
- val most_recent_event_time = PersistentData.getMostRecentAlarmTime(identifier_string)
- if (now - most_recent_event_time > periodicity_in_milliseconds) {
- // printe("'$identifier_string' - time to trigger")
- do_action()
- PersistentData.setMostRecentAlarmTime(identifier_string, System.currentTimeMillis())
- // TODO: this purely mimicks the old behavior that was of printing the broadcast, refine it.
- TextFileManager.writeDebugLogStatement(
- "Received Broadcast: " + Timer.intent_map[identifier_string]!!.toString())
-
- // printv("'$identifier_string - trigger - ${System.currentTimeMillis() - t1}")
- } else {
- // printi("'$identifier_string' - not yet time to trigger")
- // printv("'$identifier_string - not trigger - ${System.currentTimeMillis() - t1}")
- }
- }
-
- /* Abstracted timing logic for sessions that have a duration to their recording session. All
- * events that have a timed on-off pattern run through this logic. We check the event's current
- * state, recorded (PersistentData) status, compare that to the current timer values for what
- * the state SHOULD be, and also set off timers to in an attempt to get a well run_all_app_logic
- * check. (we pad with an extra second to ensure that check hits an inflection point where
- * action is required.) */
- fun do_an_on_off_session_check(
- now: Long,
- is_running: Boolean,
- should_turn_off_at: Long,
- should_turn_on_again_at: Long,
- identifier_string: String,
- intent_off_string: String,
- on_action: () -> Unit,
- off_action: () -> Unit,
- ) {
- // val t1 = System.currentTimeMillis()
- if (is_running && now <= should_turn_off_at) {
- // printw("'$identifier_string' is running, not time to turn of")
- // printv("'$identifier_string - is running - ${System.currentTimeMillis() - t1}")
- return
- }
-
- // running, should be off, off is in the past
- if (is_running && should_turn_off_at < now) {
- // printi("'$identifier_string' time to turn off")
- off_action()
- val should_turn_on_again_at_safe = should_turn_on_again_at + 1000 // add a second to ensure we pass the timer
- print("setting ON TIMER for $identifier_string to $should_turn_on_again_at_safe")
- timer!!.setupSingleAlarmAt(should_turn_on_again_at_safe, Timer.intent_map[identifier_string]!!)
- // printv("'$identifier_string - turn off - ${System.currentTimeMillis() - t1}")
- }
-
- // not_running, should turn on is still in the future, do nothing
- if (!is_running && should_turn_on_again_at >= now) {
- // printw("'$identifier_string' correctly off")
- // printv("'$identifier_string - correctly off - ${System.currentTimeMillis() - t1}")
- return
- }
-
- // not running, should be on, (on is in the past)
- if (!is_running && should_turn_on_again_at < now) {
- // always get the current time, the now value could be stale - unlikely but possible we
- // care that we get data, not that data be rigidly accurate to a clock.
- PersistentData.setMostRecentAlarmTime(identifier_string, System.currentTimeMillis())
- // printe("'$identifier_string' turn it on!")
- on_action()
- val should_turn_off_at_safe = should_turn_off_at + 1000 // add a second to ensure we pass the timer
- print("setting OFF TIMER for $identifier_string to $should_turn_off_at_safe")
- timer!!.setupSingleAlarmAt(should_turn_off_at_safe, Timer.intent_map[intent_off_string]!!)
- // printv("'$identifier_string - on action - ${System.currentTimeMillis() - t1}")
- }
- }
-
- /* If there is something with app state logic that should be idempotently checked, stick it
- * here. Returns the value used for the current time. @Synchronized because this is the core
- * logic loop. Provided potentially-expensive operations, like upload logic, run on anynchronously
- * and with reasonably widely separated real-time values, */
- @Synchronized
- fun run_all_app_logic(): Long {
- PersistentData.appOnRunAllLogic = Date(System.currentTimeMillis()).toLocaleString()
-
- val now = System.currentTimeMillis()
- // ALL of these actions wait until the participant is registered
- if (!PersistentData.getIsRegistered())
- return now
-
- // These are currently syncronous (block) unless they say otherwise, profiling was done
- // on a Pixel 6. No-action always measures 0-1ms.
- do_new_files_check(now) // always 10s of ms (30-70ms)
- do_heartbeat_check(now) // always 10s of ms (30-70ms)
- accelerometer_logic(now)
- gyro_logic(now) // on action ~20-50ms, off action 10-20ms
- gps_logic(now) // on acction <10-20ms, off action ~2ms (yes two)
- ambient_audio_logic(now) // asynchronous when stopping because it has to encrypt
- do_fcm_upload_logic_check(now) // asynchronous, runs network request on a thread.
- do_wifi_logic_check(now) // on action <10-40ms
- do_upload_logic_check(now) // asynchronous, runs network request on a thread, single digit ms.
- do_new_surveys_check(now) // asynchronous, runs network request on a thread, single digit ms.
- do_new_device_settings_check(now) // asynchronous, runs network request on a thread, single digit ms.
- do_survey_notifications_check(now) // 1 survey notification <10-30ms.
- // highest total time was 159ms, but insufficient data points to be confident.
- // printd("run_all_app_logic total time - ${System.currentTimeMillis() - now}")
- return now
- }
-
- fun accelerometer_logic(now: Long) {
- // accelerometer may not exist, or be disabled for the study, but it does not require permissions.
- if (!PersistentData.getAccelerometerEnabled() || !accelerometerListener!!.exists)
- return
-
- // assemble all the variables we need for on-off with duration
- val on_string = getString(R.string.turn_accelerometer_on)
- val off_string = getString(R.string.turn_accelerometer_off)
- val most_recent_on = PersistentData.getMostRecentAlarmTime(on_string)
- val should_turn_off_at = most_recent_on + PersistentData.getAccelerometerOnDuration()
- val should_turn_on_again_at = should_turn_off_at + PersistentData.getAccelerometerOffDuration()
- do_an_on_off_session_check(
- now,
- accelerometerListener!!.running,
- should_turn_off_at,
- should_turn_on_again_at,
- on_string,
- off_string,
- accelerometerListener!!.accelerometer_on_action,
- accelerometerListener!!.accelerometer_off_action
- )
- }
-
- fun gyro_logic(now: Long) {
- // gyro may not exist, or be disabled for the study, but it does not require permissions.
- if (!PersistentData.getGyroscopeEnabled() || !gyroscopeListener!!.exists)
- return
-
- // assemble all the variables we need for on-off with duration
- val on_string = getString(R.string.turn_gyroscope_on)
- val off_string = getString(R.string.turn_gyroscope_off)
- val most_recent_on = PersistentData.getMostRecentAlarmTime(on_string)
- val should_turn_off_at = most_recent_on + PersistentData.getGyroscopeOnDuration()
- val should_turn_on_again_at = should_turn_off_at + PersistentData.getGyroscopeOffDuration()
- do_an_on_off_session_check(
- now,
- gyroscopeListener!!.running,
- should_turn_off_at,
- should_turn_on_again_at,
- on_string,
- off_string,
- gyroscopeListener!!.gyro_on_action,
- gyroscopeListener!!.gyro_off_action
- )
- }
-
- fun gps_logic(now: Long) {
- // GPS (location service) always _exists to a degree_, checked inside the gpsListener,
- // but may not be enabled on a study. GPS requires permissions.
- if (!PermissionHandler.confirmGps(applicationContext))
- return
-
- // assemble all the variables we need for on-off with duration
- val on_string = getString(R.string.turn_gps_on)
- val off_string = getString(R.string.turn_gps_off)
- val most_recent_on = PersistentData.getMostRecentAlarmTime(on_string)
- val should_turn_off_at = most_recent_on + PersistentData.getGpsOnDuration()
- val should_turn_on_again_at = should_turn_off_at + PersistentData.getGpsOffDuration()
- do_an_on_off_session_check(
- now,
- gpsListener!!.running,
- should_turn_off_at,
- should_turn_on_again_at,
- on_string,
- off_string,
- gpsListener!!.gps_on_action,
- gpsListener!!.gps_off_action
- )
- }
-
- fun ambient_audio_logic(now: Long) {
- // check permissions and enablement
- if (!PermissionHandler.confirmAmbientAudioCollection(applicationContext))
- return
-
- val on_string = getString(R.string.turn_ambient_audio_on)
- val off_string = getString(R.string.turn_ambient_audio_off)
- val most_recent_on = PersistentData.getMostRecentAlarmTime(on_string)
- val should_turn_off_at = most_recent_on + PersistentData.getAmbientAudioOnDuration()
- val should_turn_on_again_at = should_turn_off_at + PersistentData.getAmbientAudioOffDuration()
-
- // ambiant audio needs the app context at runtime (we write very consistent code)
- val ambient_audio_on = {
- AmbientAudioListener.startRecording(applicationContext)
- }
- do_an_on_off_session_check(
- now,
- AmbientAudioListener.isCurrentlyRunning,
- should_turn_off_at,
- should_turn_on_again_at,
- on_string,
- off_string,
- ambient_audio_on,
- AmbientAudioListener.ambient_audio_off_action
- )
- }
-
- fun do_wifi_logic_check(now: Long) {
- // wifi has permissions and may be disabled on the study
- if (!PermissionHandler.confirmWifi(applicationContext))
- return
-
- val event_string = getString(R.string.run_wifi_log)
- val event_frequency = PersistentData.getWifiLogFrequency()
- val wifi_do_action = { // wifi will need some attention to convert to kotlin...
- WifiListener.scanWifi()
- }
- do_an_event_session_check(now, event_string, event_frequency, wifi_do_action)
- }
-
- fun do_upload_logic_check(now: Long) {
- val upload_string = applicationContext.getString(R.string.upload_data_files_intent)
- val periodicity = PersistentData.getUploadDataFilesFrequency()
- val do_uploads_action = {
- PostRequest.uploadAllFiles()
- }
- do_an_event_session_check(now, upload_string, periodicity, do_uploads_action)
- }
-
- fun do_fcm_upload_logic_check(now: Long) {
- // we can just literally hardcode this one, sendFcmToken is this plus a timer
- val event_string = applicationContext.getString(R.string.fcm_upload)
- val send_fcm_action = {
- val fcm_token = PersistentData.getFCMInstanceID()
- if (fcm_token != null)
- PostRequest.sendFCMInstanceID(fcm_token)
- }
- do_an_event_session_check(now, event_string, FCM_TIMER, send_fcm_action)
- }
-
- fun do_heartbeat_check(now: Long) {
- val event_string = getString(R.string.heartbeat_intent)
- val periodicity = HEARTBEAT_TIMER
- val heartbeat_action = {
- PostRequest.sendHeartbeat()
- }
- do_an_event_session_check(now, event_string, periodicity, heartbeat_action)
- }
-
- fun do_new_files_check(now: Long) {
- val event_string = getString(R.string.create_new_data_files_intent)
- val periodicity = PersistentData.getCreateNewDataFilesFrequency()
- val new_files_action = {
- TextFileManager.makeNewFilesForEverything()
- }
- do_an_event_session_check(now, event_string, periodicity, new_files_action)
- }
-
- fun do_new_surveys_check(now: Long) {
- val event_string = getString(R.string.check_for_new_surveys_intent)
- val periodicity = PersistentData.getCheckForNewSurveysFrequency()
- val dowwnload_surveys_action = {
- SurveyDownloader.downloadSurveys(applicationContext, null)
- }
- do_an_event_session_check(now, event_string, periodicity, dowwnload_surveys_action)
- }
-
- fun do_new_device_settings_check(now: Long) {
- val event_string = getString(R.string.check_for_new_device_settings_intent)
- val download_device_settings_action = {
- SetDeviceSettings.dispatchUpdateDeviceSettings()
- }
- do_an_event_session_check(now, event_string, DEVICE_SETTINGS_UPDATE_PERIODICITY, download_device_settings_action)
- }
-
- /** Checks for the current expected state for survey notifications, and the app state for
- * scheduled alarms. */
- fun do_survey_notifications_check(now: Long) {
- // val t1 = System.currentTimeMillis()
- // var counter = 0
- for (surveyId in PersistentData.getSurveyIds()) {
- var app_state_says_on = PersistentData.getSurveyNotificationState(surveyId)
- var alarm_in_past = PersistentData.getMostRecentSurveyAlarmTime(surveyId) < now
-
- // the behavior is that it ... replaces the notification.
- if ((app_state_says_on || alarm_in_past) && !isNotificationActive(applicationContext, surveyId)) {
- // this calls PersistentData.setSurveyNotificationState
- displaySurveyNotification(applicationContext, surveyId)
- // counter++
- }
-
- // TODO: fix this naming mismatch.
- // Never call this:
- // timer!!.cancelAlarm(Intent(surveyId)) // BAD!
- // setMostRecentSurveyAlarmTime is called in Timer.setupSurveyAlarm (when the alarm
- // is set in the scheduler logic), e.g. the application state is updated to say that
- // the _next_ survey alarm time is at X o'clock - there is a naming mismatch.
-
- // if there is no alarm set for this survey, set it.
- if (!timer!!.alarmIsSet(Intent(surveyId)))
- SurveyScheduler.scheduleSurvey(surveyId)
- }
- // printv("$counter survey notifications took ${System.currentTimeMillis() - t1} ms")
- }
-
- /*##########################################################################################
- ############## code related to onStartCommand and binding to an activity ###################
- ##########################################################################################*/
-
- override fun onBind(arg0: Intent?): IBinder? {
- return BackgroundServiceBinder()
- }
-
- /**A public "Binder" class for Activities to access.
- * Provides a (safe) handle to the Main Service using the onStartCommand code used in every
- * RunningBackgroundServiceActivity */
- inner class BackgroundServiceBinder : Binder() {
- val service: MainService
- get() = this@MainService
- }
-
- /*##############################################################################
- ########################## Android Service Lifecycle ###########################
- ##############################################################################*/
-
- /** The BackgroundService is meant to be all the time, so we return START_STICKY */
- override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
- // Log.d("BackgroundService onStartCommand", "started with flag " + flags );
- TextFileManager.writeDebugLogStatement(
- System.currentTimeMillis().toString() + " started with flag " + flags)
- val now = System.currentTimeMillis()
- val millisecondsSincePrevious = now - foregroundServiceLastStarted
-
- // if it has been FOREGROUND_SERVICE_TIMER or longer since the last time we started the
- // foreground service notification, start it again.
- if (foregroundServiceLastStarted == 0L || millisecondsSincePrevious > FOREGROUND_SERVICE_NOTIFICATION_TIMER) {
- val intent_to_start_foreground_service = Intent(applicationContext, MainService::class.java)
- val intent_flags = pending_intent_flag_fix(PendingIntent.FLAG_UPDATE_CURRENT) // no flags
- val onStartCommandPendingIntent = PendingIntent.getService(
- applicationContext, 0, intent_to_start_foreground_service, intent_flags
- )
- val notification = Notification.Builder(applicationContext, NOTIFICATION_CHANNEL_ID)
- .setContentTitle("Beiwe App")
- .setContentText("Beiwe data collection running")
- .setSmallIcon(R.mipmap.ic_launcher)
- .setContentIntent(onStartCommandPendingIntent)
- .setTicker("Beiwe data collection running in the background, no action required")
- .build()
-
- // multiple sources recommend an ID of 1 because it works. documentation is very spotty about this
- startForeground(1, notification)
- foregroundServiceLastStarted = now
- }
-
- PersistentData.serviceStartCommand = Date(System.currentTimeMillis()).toLocaleString()
-
- // onStartCommand is called every 30 seconds due to repeating high-priority-or-whatever
- // alarms, so we will stick a core logic check here.
- // printd("run_all_app_logic - onStartCommand")
- run_all_app_logic()
-
- // We want this service to continue running until it is explicitly stopped, so return sticky.
- return START_STICKY
- // in testing out this restarting behavior for the service it is entirely unclear if changing
- // this return will have any observable effect despite the documentation's claim that it does.
- // return START_REDELIVER_INTENT;
- }
-
- // the rest of these are ~identical
- override fun onTaskRemoved(rootIntent: Intent?) {
- // Log.d("BackroundService onTaskRemoved", "onTaskRemoved called with intent: " + rootIntent.toString() );
- TextFileManager.writeDebugLogStatement("onTaskRemoved called with intent: $rootIntent")
- PersistentData.serviceOnTaskRemoved = Date(System.currentTimeMillis()).toLocaleString()
- restartService()
- }
-
- override fun onUnbind(intent: Intent?): Boolean {
- // Log.d("BackroundService onUnbind", "onUnbind called with intent: " + intent.toString() );
- TextFileManager.writeDebugLogStatement("onUnbind called with intent: $intent")
- PersistentData.serviceOnUnbind = Date(System.currentTimeMillis()).toLocaleString()
- restartService()
- return super.onUnbind(intent)
- }
-
- override fun onDestroy() { // Log.w("BackgroundService", "BackgroundService was destroyed.");
- // note: this does not run when the service is killed in a task manager, OR when the stopService() function is called from debugActivity.
- TextFileManager.writeDebugLogStatement("BackgroundService was destroyed.")
- PersistentData.serviceOnDestroy = Date(System.currentTimeMillis()).toLocaleString()
- restartService()
- super.onDestroy()
- }
-
- override fun onLowMemory() { // Log.w("BackroundService onLowMemory", "Low memory conditions encountered");
- TextFileManager.writeDebugLogStatement("onLowMemory called.")
- PersistentData.serviceOnLowMemory = Date(System.currentTimeMillis()).toLocaleString()
- restartService()
- }
-
- override fun onTrimMemory(level: Int) {
- // Log.w("BackroundService onTrimMemory", "Trim memory conditions encountered");
- TextFileManager.writeDebugLogStatement("onTrimMemory called.")
- PersistentData.serviceOnTrimMemory = Date(System.currentTimeMillis()).toLocaleString()
- super.onTrimMemory(level)
- }
-
- /** Stops the BackgroundService instance, development tool */
- fun stop() {
- if (BuildConfig.APP_IS_BETA)
- this.stopSelf()
- }
-
- /** Sets a timer that starts the service if it is not running after a half second. */
- fun restartService() {
- val restartServiceIntent = Intent(applicationContext, this.javaClass)
- restartServiceIntent.setPackage(packageName)
- val restartServicePendingIntent = PendingIntent.getService(
- applicationContext,
- 1,
- restartServiceIntent,
- pending_intent_flag_fix(PendingIntent.FLAG_ONE_SHOT)
- )
- // kotlin port action turned this into a very weird setter syntax using [] access...
- (applicationContext.getSystemService(ALARM_SERVICE) as AlarmManager).set(
- AlarmManager.ELAPSED_REALTIME,
- SystemClock.elapsedRealtime() + 500,
- restartServicePendingIntent
- )
- }
-
- /** We sometimes need to restart the background service */
- fun exit_and_restart_background_service() {
- TextFileManager.writeDebugLogStatement("manually restarting background service")
- // if this takes more than 500ms to restart, the app will ~crash... hmm. This is fine.
- restartService()
- System.exit(0)
- }
-
- // static assets
- companion object {
- // I guess we need access to this one in static contexts...
- public var timer: Timer? = null
-
- // localHandle is how static scopes access the currently instantiated main service.
- // It is to be used ONLY to register new surveys with the running main service, because
- // that code needs to be able to update the IntentFilters associated with timerReceiver.
- // This is Really Hacky and terrible style, but it is okay because the scheduling code can only ever
- // begin to run with an already fully instantiated main service.
- var localHandle: MainService? = null
-
- private var foregroundServiceLastStarted = 0L
-
- // FIXME: in order to make this non-static we probably need to port PostReqeuest to kotlin
- /** create timers that will trigger events throughout the program, and
- * register the custom Intents with the controlMessageReceiver. */
- @JvmStatic
- fun registerTimers(applicationContext: Context) {
- timer = Timer(localHandle!!)
- val filter = IntentFilter()
- filter.addAction(applicationContext.getString(R.string.turn_accelerometer_off))
- filter.addAction(applicationContext.getString(R.string.turn_accelerometer_on))
- filter.addAction(applicationContext.getString(R.string.turn_ambient_audio_off))
- filter.addAction(applicationContext.getString(R.string.turn_ambient_audio_on))
- filter.addAction(applicationContext.getString(R.string.turn_gyroscope_on))
- filter.addAction(applicationContext.getString(R.string.turn_gyroscope_off))
- filter.addAction(applicationContext.getString(R.string.turn_bluetooth_on))
- filter.addAction(applicationContext.getString(R.string.turn_bluetooth_off))
- filter.addAction(applicationContext.getString(R.string.turn_gps_on))
- filter.addAction(applicationContext.getString(R.string.turn_gps_off))
- filter.addAction(applicationContext.getString(R.string.signout_intent))
- filter.addAction(applicationContext.getString(R.string.voice_recording))
- filter.addAction(applicationContext.getString(R.string.run_wifi_log))
- filter.addAction(applicationContext.getString(R.string.upload_data_files_intent))
- filter.addAction(applicationContext.getString(R.string.create_new_data_files_intent))
- filter.addAction(applicationContext.getString(R.string.check_for_new_surveys_intent))
- filter.addAction(applicationContext.getString(R.string.check_for_sms_enabled))
- filter.addAction(applicationContext.getString(R.string.check_for_call_log_enabled))
- filter.addAction(applicationContext.getString(R.string.check_if_ambient_audio_recording_is_enabled))
- filter.addAction(applicationContext.getString(R.string.fcm_upload))
- filter.addAction(applicationContext.getString(R.string.check_for_new_device_settings_intent))
- filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
- filter.addAction("crashBeiwe")
- filter.addAction("enterANR")
-
- for (surveyId in PersistentData.getSurveyIds()) {
- filter.addAction(surveyId)
- }
- applicationContext.registerReceiver(localHandle!!.timerReceiver, filter)
- }
-
- /**Refreshes the logout timer.
- * This function has a THEORETICAL race condition, where the BackgroundService is not fully instantiated by a session activity,
- * in this case we log an error to the debug log, print the error, and then wait for it to crash. In testing on a (much) older
- * version of the app we would occasionally see the error message, but we have never (august 10 2015) actually seen the app crash
- * inside this code. */
- fun startAutomaticLogoutCountdownTimer() {
- if (timer == null) {
- Log.e("bacgroundService", "timer is null, BackgroundService may be about to crash, the Timer was null when the BackgroundService was supposed to be fully instantiated.")
- TextFileManager.writeDebugLogStatement("our not-quite-race-condition encountered, Timer was null when the BackgroundService was supposed to be fully instantiated")
- }
- timer!!.setupExactSingleAlarm(PersistentData.getTimeBeforeAutoLogout(), Timer.signoutIntent)
- PersistentData.loginOrRefreshLogin()
- }
-
- /** cancels the signout timer */
- fun clearAutomaticLogoutCountdownTimer() {
- timer!!.cancelAlarm(Timer.signoutIntent)
- }
-
- /** The Timer requires the BackgroundService in order to create alarms, hook into that functionality here. */
- @JvmStatic
- fun setSurveyAlarm(surveyId: String?, alarmTime: Calendar?) {
- timer!!.startSurveyAlarm(surveyId!!, alarmTime!!)
- }
-
- @JvmStatic
- fun cancelSurveyAlarm(surveyId: String?) {
- timer!!.cancelAlarm(Intent(surveyId))
- }
- }
+package org.beiwe.app
+
+import android.app.*
+import android.content.BroadcastReceiver
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.content.ServiceConnection
+import android.content.pm.PackageManager
+import android.graphics.Color
+import android.net.ConnectivityManager
+import android.net.Uri
+import android.os.*
+import android.util.Log
+import com.google.android.gms.tasks.OnCompleteListener
+import com.google.android.gms.tasks.Task
+import com.google.firebase.iid.FirebaseInstanceId
+import com.google.firebase.iid.InstanceIdResult
+import io.sentry.Sentry
+import io.sentry.android.AndroidSentryClientFactory
+import io.sentry.dsn.InvalidDsnException
+import org.beiwe.app.PermissionHandler.checkBluetoothPermissions
+import org.beiwe.app.PermissionHandler.confirmBluetooth
+import org.beiwe.app.PermissionHandler.confirmCallLogging
+import org.beiwe.app.PermissionHandler.confirmOmniRing
+import org.beiwe.app.PermissionHandler.confirmTexts
+import org.beiwe.app.listeners.AccelerometerListener
+import org.beiwe.app.listeners.AmbientAudioListener
+import org.beiwe.app.listeners.BluetoothListener
+import org.beiwe.app.listeners.CallLogger
+import org.beiwe.app.listeners.GPSListener
+import org.beiwe.app.listeners.GyroscopeListener
+import org.beiwe.app.listeners.MMSSentLogger
+import org.beiwe.app.listeners.OmniringListener
+import org.beiwe.app.listeners.PowerStateListener
+import org.beiwe.app.listeners.SmsSentLogger
+import org.beiwe.app.listeners.WifiListener
+import org.beiwe.app.networking.PostRequest
+import org.beiwe.app.networking.SurveyDownloader
+import org.beiwe.app.storage.*
+import org.beiwe.app.survey.SurveyScheduler
+import org.beiwe.app.ui.user.LoginActivity
+import org.beiwe.app.ui.utils.SurveyNotifications.displaySurveyNotification
+import org.beiwe.app.ui.utils.SurveyNotifications.isNotificationActive
+import java.util.*
+
+// Notification Channel constants
+const val NOTIFICATION_CHANNEL_ID = "_service_channel"
+const val NOTIFICATION_CHANNEL_NAME = "Beiwe Data Collection" // user facing name, seen if they hold press the notification
+
+// Timer constants
+const val FCM_TIMER = 1000L * 60 * 30 // 30 minutes between sending fcm checkins
+const val DEVICE_SETTINGS_UPDATE_PERIODICITY = 1000L * 60 * 30 // 30 between checking for updated device settings updates
+const val HEARTBEAT_TIMER = 1000L * 60 * 5 // 5 minutes between sending heartbeats
+
+// set our repeating timers to 30 seconds (threadhandler is offset by half the period)
+const val FOREGROUND_SERVICE_RESTART_PERIODICITY = 1000L * 30
+const val THREADHANDLER_PERIODICITY = 1000L * 30
+
+// 6 hours for a foreground service notification, this is JUST the notification, not the service itself.
+const val FOREGROUND_SERVICE_NOTIFICATION_TIMER = 1000L * 60 * 60 * 6
+
+const val BLLUETOOTH_MESSAGE_1 = "bluetooth Failure, device should not have gotten to this line of code"
+const val BLLUETOOTH_MESSAGE_2 = "Device does not support bluetooth LE, bluetooth features disabled."
+const val FCM_ERROR_MESSAGE = "Unable to get FCM token, will not be able to receive push notifications."
+
+// We were getting some weird null intent exceptions with invalid stack traces pointing to line 2 of
+// this file. Line 2 is either an import, a package declaration, an error suppression annotation, or
+// blank. All overridden functions in this file that have non-primitive variables (usually intents)
+// must be declared as optional and handle that null case (usually we ignore it).
+
+class MainService : Service() {
+ // the various listeners for sensor data
+ var gpsListener: GPSListener? = null
+ var powerStateListener: PowerStateListener? = null
+ var accelerometerListener: AccelerometerListener? = null
+ var gyroscopeListener: GyroscopeListener? = null
+ var bluetoothListener: BluetoothListener? = null
+ var omniringListener: OmniringListener? = null
+
+ // these assets don't require android assets, they can go in the common init.
+ val background_handlerThread = HandlerThread("background_handler_thread")
+ var background_handler: Handler
+ var background_looper: Looper
+ var hasInitializedOnce = false
+
+ init {
+ background_handlerThread.start()
+ background_looper = background_handlerThread.looper
+ background_handler = Handler(background_looper)
+ }
+
+ /*##############################################################################################
+ ############################## App Core Setup ###########################
+ ##############################################################################################*/
+
+ /** onCreate is essentially the constructor for the service, initialize variables here. */
+ override fun onCreate() {
+ localHandle = this // yes yes, gross, I know. must instantiate before registerTimers()
+
+ try {
+ val sentryDsn = BuildConfig.SENTRY_DSN
+ Sentry.init(sentryDsn, AndroidSentryClientFactory(applicationContext))
+ } catch (ie: InvalidDsnException) {
+ Sentry.init(AndroidSentryClientFactory(applicationContext))
+ }
+
+ // report errors from the service to sentry only when this is not the development build
+ if (!BuildConfig.APP_IS_DEV)
+ Thread.setDefaultUncaughtExceptionHandler(CrashHandler(applicationContext))
+
+ // Accessing a survey requires thhe user opening the app or an activet survey notification,
+ // which means the background service is always running before that point, even in the
+ // corner case of when the background starts an system-on.
+
+ PersistentData.initialize(applicationContext)
+ PersistentData.setNotTakingSurvey()
+
+ // Initialize everything that is necessary for the app!
+ initializeFireBaseIDToken()
+ TextFileManager.initialize(applicationContext)
+ PostRequest.initialize(applicationContext)
+ registerTimers(applicationContext)
+ createNotificationChannel()
+ doSetup()
+
+ // dispatch the ThreadHandler based run_all_app_logic call with a 1/2 duration offset.
+ background_handler.postDelayed(periodic_run_app_logic, THREADHANDLER_PERIODICITY / 2)
+ val start_time = Date(System.currentTimeMillis()).toLocaleString()
+ PersistentData.appOnServiceStart = start_time
+ if (!this.hasInitializedOnce) {
+ PersistentData.appOnServiceStartFirstRun = start_time
+ this.hasInitializedOnce = true
+ }
+ }
+
+ // namespace hack, see comment
+ fun get_periodic_run_app_logic(): () -> Unit = periodic_run_app_logic
+ val periodic_run_app_logic: () -> Unit = {
+ // printd("run_all_app_logic - ThreadHandler")
+ run_all_app_logic()
+ // in the scope of this closure "periodic_run_app_logic" doesn't exist, we need to access it, not referency it.
+ background_handler.postDelayed(get_periodic_run_app_logic(), THREADHANDLER_PERIODICITY)
+ }
+
+ fun doSetup() {
+ // Accelerometer, gyro, power state, and wifi don't need permissions or they are checked in
+ // the broadcastreceiver logic
+ startPowerStateListener()
+ gpsListener = GPSListener(applicationContext)
+ WifiListener.initialize(applicationContext)
+
+ if (PersistentData.getAccelerometerEnabled())
+ accelerometerListener = AccelerometerListener(applicationContext)
+ if (PersistentData.getGyroscopeEnabled())
+ gyroscopeListener = GyroscopeListener(applicationContext)
+
+ // Bluetooth, wifi, gps, calls, and texts need permissions
+ if (confirmBluetooth(applicationContext))
+ initializeBluetooth()
+
+ if (confirmOmniRing(applicationContext))
+ initializeOmniRing()
+
+ if (confirmTexts(applicationContext)) {
+ startSmsSentLogger()
+ startMmsSentLogger()
+ } else if (PersistentData.getTextsEnabled()) {
+ sendBroadcast(Timer.checkForSMSEnabledIntent)
+ }
+ if (confirmCallLogging(applicationContext))
+ startCallLogger()
+ else if (PersistentData.getCallLoggingEnabled())
+ sendBroadcast(Timer.checkForCallsEnabledIntent)
+
+ // Only do the following if the device is registered
+ if (PersistentData.getIsRegistered()) {
+ DeviceInfo.initialize(applicationContext) // if at registration this has already been initialized. (we don't care.)
+ startTimers()
+ }
+ }
+
+ private fun createNotificationChannel() {
+ // setup the notification channel so the service can run in the foreground
+ val chan = NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT)
+ chan.lightColor = Color.BLUE
+ chan.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
+ chan.setSound(null, null)
+ val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
+ manager.createNotificationChannel(chan)
+ }
+
+ /*#############################################################################
+ ######################### Starters #######################
+ #############################################################################*/
+ private val connection = object : ServiceConnection {
+ override fun onServiceConnected(className: ComponentName, service: IBinder) {
+ val binder = service as OmniringListener.LocalBinder
+ omniringListener = binder.getService()
+ Log.d("omniring", "onServiceConnected: omniringListener bound")
+ }
+
+ override fun onServiceDisconnected(arg0: ComponentName) {
+ omniringListener = null
+ Log.d("omniring", "onServiceConnected: omniringListener unbound")
+ }
+ }
+
+
+ /** Initializes the Bluetooth listener
+ * Bluetooth has several checks to make sure that it actually exists on the device with the
+ * capabilities we need. Checking for Bluetooth LE is necessary because it is an optional
+ * extension to Bluetooth 4.0. */
+ fun initializeBluetooth() {
+ // Note: the Bluetooth listener is a BroadcastReceiver, which means it must have a 0-argument
+ // constructor in order for android to instantiate it on broadcast receipts. The following
+ // check must be made, but it requires a Context that we cannot pass into the
+ // BluetoothListener, so we do the check in the BackgroundService.
+ if (applicationContext.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
+ if (PersistentData.getBluetoothEnabled()) {
+ bluetoothListener = BluetoothListener()
+ if (bluetoothListener!!.isBluetoothEnabled) {
+ val intent_filter =
+ IntentFilter("android.bluetooth.adapter.action.STATE_CHANGED")
+ registerReceiver(bluetoothListener, intent_filter)
+ } else {
+ // TODO: Track down why this error occurs, cleanup. The above check should be for
+ // the (new) doesBluetoothCapabilityExist function instead of isBluetoothEnabled
+ Log.e("Main Service", BLLUETOOTH_MESSAGE_1)
+ TextFileManager.writeDebugLogStatement(BLLUETOOTH_MESSAGE_1)
+ }
+ }
+ } else {
+ if (PersistentData.getBluetoothEnabled()) {
+ TextFileManager.writeDebugLogStatement(BLLUETOOTH_MESSAGE_2)
+ Log.w("MainS bluetooth init", BLLUETOOTH_MESSAGE_2)
+ }
+ bluetoothListener = null
+ }
+ }
+
+ fun initializeOmniRing() {
+ if (applicationContext.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
+ if (PersistentData.getOmniRingEnabled()) {
+ val intent = Intent(this, OmniringListener::class.java).also { intent ->
+ bindService(intent, connection, Context.BIND_AUTO_CREATE)
+ }
+ Log.d("omniring", "initializeBluetoothAndOmniring: starting omniring")
+ startService(intent)
+ }
+ } else {
+ if (PersistentData.getOmniRingEnabled()) {
+ TextFileManager.writeDebugLogStatement(BLLUETOOTH_MESSAGE_2)
+ Log.w("MainS omniring init", BLLUETOOTH_MESSAGE_2)
+ }
+ omniringListener = null
+ }
+ }
+
+ /** Initializes the sms logger. */
+ fun startSmsSentLogger() {
+ val smsSentLogger = SmsSentLogger(Handler(), applicationContext)
+ this.contentResolver.registerContentObserver(
+ Uri.parse("content://sms/"), true, smsSentLogger)
+ }
+
+ fun startMmsSentLogger() {
+ val mmsMonitor = MMSSentLogger(Handler(), applicationContext)
+ this.contentResolver.registerContentObserver(
+ Uri.parse("content://mms/"), true, mmsMonitor)
+ }
+
+ /** Initializes the call logger. */
+ private fun startCallLogger() {
+ val callLogger = CallLogger(Handler(), applicationContext)
+ this.contentResolver.registerContentObserver(
+ Uri.parse("content://call_log/calls/"), true, callLogger)
+ }
+
+ /** Initializes the PowerStateListener.
+ * The PowerStateListener requires the ACTION_SCREEN_OFF and ACTION_SCREEN_ON intents be
+ * registered programatically. They do not work if registered in the app's manifest. Same for
+ * the ACTION_POWER_SAVE_MODE_CHANGED and ACTION_DEVICE_IDLE_MODE_CHANGED filters, though they
+ * are for monitoring deeper power state changes in 5.0 and 6.0, respectively. */
+ private fun startPowerStateListener() {
+ if (powerStateListener == null) {
+ val filter = IntentFilter()
+ filter.addAction(Intent.ACTION_SCREEN_ON)
+ filter.addAction(Intent.ACTION_SCREEN_OFF)
+ if (Build.VERSION.SDK_INT >= 21)
+ filter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)
+ if (Build.VERSION.SDK_INT >= 23)
+ filter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED)
+ powerStateListener = PowerStateListener()
+ registerReceiver(powerStateListener, filter)
+ PowerStateListener.start(applicationContext)
+ }
+ }
+
+ /** Gets, sets, and pushes the FCM token to the backend. */
+ fun initializeFireBaseIDToken() {
+ // Set up the oncomplete listener for the FCM getter code, which in turn sets up a thread
+ // that will wait until the participant is registered to actually push it off to the server.
+ val fcm_closure = OnCompleteListener { task: Task ->
+ // If the task failed, log the error and return, we will resend in the firebase
+ // token-changed code, or the FCM_TIMER periodic event.
+ if (!task.isSuccessful) {
+ Log.e("FCM", FCM_ERROR_MESSAGE, task.exception)
+ TextFileManager.writeDebugLogStatement("$FCM_ERROR_MESSAGE(1)")
+ return@OnCompleteListener
+ }
+
+ // Get new Instance ID token - literally can't access task.result in blocker_closure ...?!
+ val taskResult = task.result
+ if (taskResult == null) {
+ TextFileManager.writeDebugLogStatement("$FCM_ERROR_MESSAGE(2)")
+ return@OnCompleteListener
+ }
+
+ // We need to wait until the participant is registered to send the fcm token.
+ // (This is a Runnable because we need to return early in an error case with @Runnable)
+ val blocker_closure = Runnable {
+ while (!PersistentData.getIsRegistered()) {
+ try {
+ Thread.sleep(1000)
+ } catch (ignored: InterruptedException) {
+ TextFileManager.writeDebugLogStatement("$FCM_ERROR_MESSAGE(3)")
+ return@Runnable
+ }
+ }
+ PersistentData.setFCMInstanceID(taskResult.token)
+ PostRequest.sendFCMInstanceID(taskResult.token)
+ }
+
+ // kick off the blocker thread
+ Thread(blocker_closure, "fcm_blocker_thread").start()
+ }
+
+ // setup oncomplete listener
+ FirebaseInstanceId.getInstance().instanceId.addOnCompleteListener(fcm_closure)
+ }
+
+ /*#############################################################################
+ #################### Timer Logic #######################
+ #############################################################################*/
+
+ fun startTimers() {
+ Log.i("BackgroundService", "running startTimer logic.")
+ // printd("run_all_app_logic - startTimers")
+ run_all_app_logic()
+
+ // if Bluetooth recording is enabled and there is no scheduled next-bluetooth-enable event,
+ // set up the next Bluetooth-on alarm. (Bluetooth needs to run at absolute points in time,
+ // it should not be started if a scheduled event is missed.)
+ if (PersistentData.getBluetoothEnabled()) {
+ if (confirmBluetooth(applicationContext) && !timer!!.alarmIsSet(Timer.bluetoothOnIntent))
+ timer!!.setupExactSingleAbsoluteTimeAlarm(
+ PersistentData.getBluetoothTotalDuration(),
+ PersistentData.getBluetoothGlobalOffset(),
+ Timer.bluetoothOnIntent
+ )
+ }
+
+ // this is a repeating alarm that ensures the service is running, it starts the service if it isn't.
+ // Periodicity is FOREGROUND_SERVICE_RESTART_PERIODICITY.
+ // This is a special intent, it has a construction that targets the MainService's onStartCommand method.
+ val alarmService = applicationContext.getSystemService(ALARM_SERVICE) as AlarmManager
+ val restartServiceIntent = Intent(applicationContext, MainService::class.java)
+ restartServiceIntent.setPackage(packageName)
+ val flags = pending_intent_flag_fix(PendingIntent.FLAG_UPDATE_CURRENT)
+ // no clue what this requestcode means, it is 0 on normal pending intents
+ val repeatingRestartServicePendingIntent = PendingIntent.getService(
+ applicationContext, 1, restartServiceIntent, flags
+ )
+ alarmService.setRepeating(
+ AlarmManager.RTC_WAKEUP,
+ System.currentTimeMillis() + FOREGROUND_SERVICE_RESTART_PERIODICITY,
+ FOREGROUND_SERVICE_RESTART_PERIODICITY,
+ repeatingRestartServicePendingIntent
+ )
+ }
+
+ /**The timerReceiver is an Android BroadcastReceiver that listens for our timer events to trigger,
+ * and then runs the appropriate code for that trigger.
+ * Note: every condition has a return statement at the end; this is because the trigger survey
+ * notification action requires a fairly expensive dive into PersistantData JSON unpacking. */
+ private val timerReceiver: BroadcastReceiver = object : BroadcastReceiver() {
+ override fun onReceive(applicationContext: Context, intent: Intent?) {
+ Log.e("BackgroundService", "Received broadcast: $intent")
+ TextFileManager.writeDebugLogStatement("Received Broadcast: " + intent.toString())
+
+ if (intent == null)
+ return
+
+ val broadcastAction = intent.action
+ // printd("run_all_app_logic - timerReceiver")
+ run_all_app_logic()
+
+ /* Bluetooth timers are unlike GPS and Accelerometer because it uses an
+ * absolute-point-in-time as a trigger, and therefore we don't need to store
+ * most-recent-timer state. The Bluetooth-on action sets the corresponding Bluetooth-off
+ * timer, the Bluetooth-off action sets the next Bluetooth-on timer.*/
+ if (broadcastAction == applicationContext.getString(R.string.turn_bluetooth_on)) {
+ printe("Bluetooth on timer triggered")
+ if (!PersistentData.getBluetoothEnabled()) // return, don't set another alarm
+ return
+
+ if (checkBluetoothPermissions(applicationContext)) {
+ if (bluetoothListener != null) bluetoothListener!!.enableBLEScan()
+ } else {
+ TextFileManager.writeDebugLogStatement("user has not provided permission for Bluetooth.")
+ }
+ timer!!.setupExactSingleAlarm(PersistentData.getBluetoothOnDuration(), Timer.bluetoothOffIntent)
+ return
+ }
+
+ if (broadcastAction == applicationContext.getString(R.string.turn_bluetooth_off)) {
+ printe("Bluetooth off timer triggered")
+ if (checkBluetoothPermissions(applicationContext) && bluetoothListener != null) {
+ bluetoothListener!!.disableBLEScan()
+ }
+ timer!!.setupExactSingleAbsoluteTimeAlarm(
+ PersistentData.getBluetoothTotalDuration(),
+ PersistentData.getBluetoothGlobalOffset(),
+ Timer.bluetoothOnIntent
+ )
+ return
+ }
+
+ // I don't know if we pull this one out
+ // Signs out the user. (does not set up a timer, that is handled in activity and sign-in logic)
+ if (broadcastAction == applicationContext.getString(R.string.signout_intent)) {
+ // FIXME: does this need to run on the main thread in do_signout_check?
+ PersistentData.logout()
+ val loginPage = Intent(applicationContext, LoginActivity::class.java) // yup that is still java
+ loginPage.flags = Intent.FLAG_ACTIVITY_NEW_TASK
+ applicationContext.startActivity(loginPage)
+ return
+ }
+
+ // leave the SMS/MMS/calls logic as-is, it is like this to ensure they are never
+ // enabled until the particiant presses the accept button.
+ if (broadcastAction == applicationContext.getString(R.string.check_for_sms_enabled)) {
+ if (confirmTexts(applicationContext)) {
+ startSmsSentLogger()
+ startMmsSentLogger()
+ } else if (PersistentData.getTextsEnabled())
+ timer!!.setupExactSingleAlarm(30000L, Timer.checkForSMSEnabledIntent)
+ }
+ // logic for the call (metadata) logger
+ if (broadcastAction == applicationContext.getString(R.string.check_for_call_log_enabled)) {
+ if (confirmCallLogging(applicationContext)) {
+ startCallLogger()
+ } else if (PersistentData.getCallLoggingEnabled())
+ timer!!.setupExactSingleAlarm(30000L, Timer.checkForCallsEnabledIntent)
+ }
+
+
+ // This code has been removed, the app now explicitly checks app state, and the call
+ // to send this particular broadcast is no longer used. We will retain this for now
+ // (June 2024) in case we had a real good reason for retaining this pattern now that
+ // survey state checking.
+ // checks if the action is the id of a survey (expensive), if so pop up the notification
+ // for that survey, schedule the next alarm.
+ // if (PersistentData.getSurveyIds().contains(broadcastAction)) {
+ // // Log.i("MAIN SERVICE", "new notification: " + broadcastAction);
+ // displaySurveyNotification(applicationContext, broadcastAction!!)
+ // SurveyScheduler.scheduleSurvey(broadcastAction)
+ // return
+ // }
+
+ // these are special actions that will only run if the app device is in debug mode.
+ if (broadcastAction == "crashBeiwe" && BuildConfig.APP_IS_BETA) {
+ throw NullPointerException("beeeeeoooop.")
+ }
+ if (broadcastAction == "enterANR" && BuildConfig.APP_IS_BETA) {
+ try {
+ Thread.sleep(100000)
+ } catch (ie: InterruptedException) {
+ ie.printStackTrace()
+ }
+ }
+ }
+ }
+
+ /*##############################################################################
+ ########################## Application State Logic #############################
+ ##############################################################################*/
+
+ // TODO: if we make this use rtc time that will solve time-reset issues. Could also run a sanity check.
+ // TODO: test default (should be zero? out of PersistentData) cases.
+ // TODO: is there an advantage to sticking the callables onto a queue that is then consumed? leaning no.
+
+ /* Abstract function, checks the time, runs the action, sets the next time. */
+ fun do_an_event_session_check(
+ now: Long,
+ identifier_string: String,
+ periodicity_in_milliseconds: Long,
+ do_action: () -> Unit,
+ ) {
+ // val t1 = System.currentTimeMillis()
+ val most_recent_event_time = PersistentData.getMostRecentAlarmTime(identifier_string)
+ if (now - most_recent_event_time > periodicity_in_milliseconds) {
+ // printe("'$identifier_string' - time to trigger")
+ do_action()
+ PersistentData.setMostRecentAlarmTime(identifier_string, System.currentTimeMillis())
+ // TODO: this purely mimicks the old behavior that was of printing the broadcast, refine it.
+ TextFileManager.writeDebugLogStatement(
+ "Received Broadcast: " + Timer.intent_map[identifier_string]!!.toString())
+
+ // printv("'$identifier_string - trigger - ${System.currentTimeMillis() - t1}")
+ } else {
+ // printi("'$identifier_string' - not yet time to trigger")
+ // printv("'$identifier_string - not trigger - ${System.currentTimeMillis() - t1}")
+ }
+ }
+
+ /* Abstracted timing logic for sessions that have a duration to their recording session. All
+ * events that have a timed on-off pattern run through this logic. We check the event's current
+ * state, recorded (PersistentData) status, compare that to the current timer values for what
+ * the state SHOULD be, and also set off timers to in an attempt to get a well run_all_app_logic
+ * check. (we pad with an extra second to ensure that check hits an inflection point where
+ * action is required.) */
+ fun do_an_on_off_session_check(
+ now: Long,
+ is_running: Boolean,
+ should_turn_off_at: Long,
+ should_turn_on_at: Long,
+ intent_on_string: String,
+ intent_off_string: String,
+ on_action: () -> Unit,
+ off_action: () -> Unit,
+ ) {
+ // val t1 = System.currentTimeMillis()
+ if (is_running && now <= should_turn_off_at) {
+ print("Sensor listener service is running. Next $intent_off_string is scheduled to ${convertTimestamp(should_turn_off_at)}")
+ return
+ }
+
+ // running, should be off, off is in the past
+ if (is_running && should_turn_off_at < now) {
+ off_action()
+ val should_turn_on_at_safe = should_turn_on_at + 1000 // add a second to ensure we pass the timer
+ timer!!.setupSingleAlarmAt(should_turn_on_at_safe, Timer.intent_map[intent_on_string]!!)
+ print("Sensor listener service turned off. Next $intent_on_string is scheduled to ${convertTimestamp(should_turn_on_at_safe)}")
+ }
+
+ // not_running, should turn on is still in the future, do nothing
+ if (!is_running && should_turn_on_at >= now) {
+ print("Sensor listener service is off. Next $intent_on_string is scheduled to ${convertTimestamp(should_turn_on_at)}")
+ return
+ }
+
+ // not running, should be on, (on is in the past)
+ if (!is_running && should_turn_on_at < now) {
+ // always get the current time, the now value could be stale - unlikely but possible we
+ // care that we get data, not that data be rigidly accurate to a clock.
+ PersistentData.setMostRecentAlarmTime(intent_on_string, System.currentTimeMillis())
+ on_action()
+ val should_turn_off_at_safe = should_turn_off_at + 1000 // add a second to ensure we pass the timer
+ timer!!.setupSingleAlarmAt(should_turn_off_at_safe, Timer.intent_map[intent_off_string]!!)
+ print("Sensor listener service turned on. Next $intent_off_string is scheduled to ${convertTimestamp(should_turn_off_at_safe)}")
+ }
+ }
+
+ /* If there is something with app state logic that should be idempotently checked, stick it
+ * here. Returns the value used for the current time. @Synchronized because this is the core
+ * logic loop. Provided potentially-expensive operations, like upload logic, run on anynchronously
+ * and with reasonably widely separated real-time values, */
+ @Synchronized
+ fun run_all_app_logic(): Long {
+ PersistentData.appOnRunAllLogic = Date(System.currentTimeMillis()).toLocaleString()
+
+ val now = System.currentTimeMillis()
+ // ALL of these actions wait until the participant is registered
+ if (!PersistentData.getIsRegistered())
+ return now
+
+ // These are currently syncronous (block) unless they say otherwise, profiling was done
+ // on a Pixel 6. No-action always measures 0-1ms.
+ do_new_files_check(now) // always 10s of ms (30-70ms)
+ do_heartbeat_check(now) // always 10s of ms (30-70ms)
+ accelerometer_logic(now)
+ if (omniringListener != null)
+ omniring_logic(now)
+ gyro_logic(now) // on action ~20-50ms, off action 10-20ms
+ gps_logic(now) // on acction <10-20ms, off action ~2ms (yes two)
+ ambient_audio_logic(now) // asynchronous when stopping because it has to encrypt
+ do_fcm_upload_logic_check(now) // asynchronous, runs network request on a thread.
+ do_wifi_logic_check(now) // on action <10-40ms
+ do_upload_logic_check(now) // asynchronous, runs network request on a thread, single digit ms.
+ do_new_surveys_check(now) // asynchronous, runs network request on a thread, single digit ms.
+ do_new_device_settings_check(now) // asynchronous, runs network request on a thread, single digit ms.
+ do_survey_notifications_check(now) // 1 survey notification <10-30ms.
+ // highest total time was 159ms, but insufficient data points to be confident.
+ // printd("run_all_app_logic total time - ${System.currentTimeMillis() - now}")
+ return now
+ }
+
+ fun omniring_logic(now: Long) {
+ if (!PersistentData.getOmniRingEnabled() || omniringListener?.exists == false)
+ return
+
+ val on_string = getString(R.string.turn_omniring_on)
+ val off_string = getString(R.string.turn_omniring_off)
+ val most_recent_on = PersistentData.getMostRecentAlarmTime(on_string)
+ val should_turn_off_at = most_recent_on + PersistentData.getOmniRingOnDuration()
+ val should_turn_on_again_at =
+ should_turn_off_at + PersistentData.getOmniRingOffDuration()
+ do_an_on_off_session_check(
+ now,
+ omniringListener!!.isOnState,
+ should_turn_off_at,
+ should_turn_on_again_at,
+ on_string,
+ off_string,
+ omniringListener!!.omniring_on_action,
+ omniringListener!!.omniring_off_action
+ )
+ }
+
+ fun accelerometer_logic(now: Long) {
+ // accelerometer may not exist, or be disabled for the study, but it does not require permissions.
+ if (!PersistentData.getAccelerometerEnabled() || !accelerometerListener!!.exists)
+ return
+
+ // assemble all the variables we need for on-off with duration
+ val on_string = getString(R.string.turn_accelerometer_on)
+ val off_string = getString(R.string.turn_accelerometer_off)
+ val most_recent_on = PersistentData.getMostRecentAlarmTime(on_string)
+ val should_turn_off_at = most_recent_on + PersistentData.getAccelerometerOnDuration()
+ val should_turn_on_again_at = should_turn_off_at + PersistentData.getAccelerometerOffDuration()
+ do_an_on_off_session_check(
+ now,
+ accelerometerListener!!.running,
+ should_turn_off_at,
+ should_turn_on_again_at,
+ on_string,
+ off_string,
+ accelerometerListener!!.accelerometer_on_action,
+ accelerometerListener!!.accelerometer_off_action
+ )
+ }
+
+ fun gyro_logic(now: Long) {
+ // gyro may not exist, or be disabled for the study, but it does not require permissions.
+ if (!PersistentData.getGyroscopeEnabled() || !gyroscopeListener!!.exists)
+ return
+
+ // assemble all the variables we need for on-off with duration
+ val on_string = getString(R.string.turn_gyroscope_on)
+ val off_string = getString(R.string.turn_gyroscope_off)
+ val most_recent_on = PersistentData.getMostRecentAlarmTime(on_string)
+ val should_turn_off_at = most_recent_on + PersistentData.getGyroscopeOnDuration()
+ val should_turn_on_again_at = should_turn_off_at + PersistentData.getGyroscopeOffDuration()
+ do_an_on_off_session_check(
+ now,
+ gyroscopeListener!!.running,
+ should_turn_off_at,
+ should_turn_on_again_at,
+ on_string,
+ off_string,
+ gyroscopeListener!!.gyro_on_action,
+ gyroscopeListener!!.gyro_off_action
+ )
+ }
+
+ fun gps_logic(now: Long) {
+ // GPS (location service) always _exists to a degree_, checked inside the gpsListener,
+ // but may not be enabled on a study. GPS requires permissions.
+ if (!PermissionHandler.confirmGps(applicationContext))
+ return
+
+ // assemble all the variables we need for on-off with duration
+ val on_string = getString(R.string.turn_gps_on)
+ val off_string = getString(R.string.turn_gps_off)
+ val most_recent_on = PersistentData.getMostRecentAlarmTime(on_string)
+ val should_turn_off_at = most_recent_on + PersistentData.getGpsOnDuration()
+ val should_turn_on_again_at = should_turn_off_at + PersistentData.getGpsOffDuration()
+ do_an_on_off_session_check(
+ now,
+ gpsListener!!.running,
+ should_turn_off_at,
+ should_turn_on_again_at,
+ on_string,
+ off_string,
+ gpsListener!!.gps_on_action,
+ gpsListener!!.gps_off_action
+ )
+ }
+
+ fun ambient_audio_logic(now: Long) {
+ // check permissions and enablement
+ if (!PermissionHandler.confirmAmbientAudioCollection(applicationContext))
+ return
+
+ val on_string = getString(R.string.turn_ambient_audio_on)
+ val off_string = getString(R.string.turn_ambient_audio_off)
+ val most_recent_on = PersistentData.getMostRecentAlarmTime(on_string)
+ val should_turn_off_at = most_recent_on + PersistentData.getAmbientAudioOnDuration()
+ val should_turn_on_again_at = should_turn_off_at + PersistentData.getAmbientAudioOffDuration()
+
+ // ambiant audio needs the app context at runtime (we write very consistent code)
+ val ambient_audio_on = {
+ AmbientAudioListener.startRecording(applicationContext)
+ }
+ do_an_on_off_session_check(
+ now,
+ AmbientAudioListener.isCurrentlyRunning,
+ should_turn_off_at,
+ should_turn_on_again_at,
+ on_string,
+ off_string,
+ ambient_audio_on,
+ AmbientAudioListener.ambient_audio_off_action
+ )
+ }
+
+ fun do_wifi_logic_check(now: Long) {
+ // wifi has permissions and may be disabled on the study
+ if (!PermissionHandler.confirmWifi(applicationContext))
+ return
+
+ val event_string = getString(R.string.run_wifi_log)
+ val event_frequency = PersistentData.getWifiLogFrequency()
+ val wifi_do_action = { // wifi will need some attention to convert to kotlin...
+ WifiListener.scanWifi()
+ }
+ do_an_event_session_check(now, event_string, event_frequency, wifi_do_action)
+ }
+
+ fun do_upload_logic_check(now: Long) {
+ val upload_string = applicationContext.getString(R.string.upload_data_files_intent)
+ val periodicity = PersistentData.getUploadDataFilesFrequency()
+ val do_uploads_action = {
+ PostRequest.uploadAllFiles()
+ }
+ do_an_event_session_check(now, upload_string, periodicity, do_uploads_action)
+ }
+
+ fun do_fcm_upload_logic_check(now: Long) {
+ // we can just literally hardcode this one, sendFcmToken is this plus a timer
+ val event_string = applicationContext.getString(R.string.fcm_upload)
+ val send_fcm_action = {
+ val fcm_token = PersistentData.getFCMInstanceID()
+ if (fcm_token != null)
+ PostRequest.sendFCMInstanceID(fcm_token)
+ }
+ do_an_event_session_check(now, event_string, FCM_TIMER, send_fcm_action)
+ }
+
+ fun do_heartbeat_check(now: Long) {
+ val event_string = getString(R.string.heartbeat_intent)
+ val periodicity = HEARTBEAT_TIMER
+ val heartbeat_action = {
+ PostRequest.sendHeartbeat()
+ }
+ do_an_event_session_check(now, event_string, periodicity, heartbeat_action)
+ }
+
+ fun do_new_files_check(now: Long) {
+ val event_string = getString(R.string.create_new_data_files_intent)
+ val periodicity = PersistentData.getCreateNewDataFilesFrequency()
+ val new_files_action = {
+ TextFileManager.makeNewFilesForEverything()
+ }
+ do_an_event_session_check(now, event_string, periodicity, new_files_action)
+ }
+
+ fun do_new_surveys_check(now: Long) {
+ val event_string = getString(R.string.check_for_new_surveys_intent)
+ val periodicity = PersistentData.getCheckForNewSurveysFrequency()
+ val dowwnload_surveys_action = {
+ SurveyDownloader.downloadSurveys(applicationContext, null)
+ }
+ do_an_event_session_check(now, event_string, periodicity, dowwnload_surveys_action)
+ }
+
+ fun do_new_device_settings_check(now: Long) {
+ val event_string = getString(R.string.check_for_new_device_settings_intent)
+ val download_device_settings_action = {
+ SetDeviceSettings.dispatchUpdateDeviceSettings()
+ }
+ do_an_event_session_check(
+ now,
+ event_string,
+ DEVICE_SETTINGS_UPDATE_PERIODICITY,
+ download_device_settings_action
+ )
+ }
+
+ /** Checks for the current expected state for survey notifications, and the app state for
+ * scheduled alarms. */
+ fun do_survey_notifications_check(now: Long) {
+ // val t1 = System.currentTimeMillis()
+ // var counter = 0
+ for (surveyId in PersistentData.getSurveyIds()) {
+ var app_state_says_on = PersistentData.getSurveyNotificationState(surveyId)
+ var alarm_in_past = PersistentData.getMostRecentSurveyAlarmTime(surveyId) < now
+
+ // the behavior is that it ... replaces the notification.
+ if ((app_state_says_on || alarm_in_past) && !isNotificationActive(applicationContext, surveyId)) {
+ // this calls PersistentData.setSurveyNotificationState
+ displaySurveyNotification(applicationContext, surveyId)
+ // counter++
+ }
+
+ // TODO: fix this naming mismatch.
+ // Never call this:
+ // timer!!.cancelAlarm(Intent(surveyId)) // BAD!
+ // setMostRecentSurveyAlarmTime is called in Timer.setupSurveyAlarm (when the alarm
+ // is set in the scheduler logic), e.g. the application state is updated to say that
+ // the _next_ survey alarm time is at X o'clock - there is a naming mismatch.
+
+ // if there is no alarm set for this survey, set it.
+ if (!timer!!.alarmIsSet(Intent(surveyId)))
+ SurveyScheduler.scheduleSurvey(surveyId)
+ }
+ // printv("$counter survey notifications took ${System.currentTimeMillis() - t1} ms")
+ }
+
+ /*##########################################################################################
+ ############## code related to onStartCommand and binding to an activity ###################
+ ##########################################################################################*/
+
+ override fun onBind(arg0: Intent?): IBinder? {
+ return BackgroundServiceBinder()
+ }
+
+ /**A public "Binder" class for Activities to access.
+ * Provides a (safe) handle to the Main Service using the onStartCommand code used in every
+ * RunningBackgroundServiceActivity */
+ inner class BackgroundServiceBinder : Binder() {
+ val service: MainService
+ get() = this@MainService
+ }
+
+ /*##############################################################################
+ ########################## Android Service Lifecycle ###########################
+ ##############################################################################*/
+
+ /** The BackgroundService is meant to be all the time, so we return START_STICKY */
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ // Log.d("BackgroundService onStartCommand", "started with flag " + flags );
+ TextFileManager.writeDebugLogStatement(
+ System.currentTimeMillis().toString() + " started with flag " + flags)
+ val now = System.currentTimeMillis()
+ val millisecondsSincePrevious = now - foregroundServiceLastStarted
+
+ // if it has been FOREGROUND_SERVICE_TIMER or longer since the last time we started the
+ // foreground service notification, start it again.
+ if (foregroundServiceLastStarted == 0L || millisecondsSincePrevious > FOREGROUND_SERVICE_NOTIFICATION_TIMER) {
+ val intent_to_start_foreground_service = Intent(applicationContext, MainService::class.java)
+ val intent_flags = pending_intent_flag_fix(PendingIntent.FLAG_UPDATE_CURRENT) // no flags
+ val onStartCommandPendingIntent = PendingIntent.getService(
+ applicationContext, 0, intent_to_start_foreground_service, intent_flags
+ )
+ val notification = Notification.Builder(applicationContext, NOTIFICATION_CHANNEL_ID)
+ .setContentTitle("Beiwe App")
+ .setContentText("Beiwe data collection running")
+ .setSmallIcon(R.mipmap.ic_launcher)
+ .setContentIntent(onStartCommandPendingIntent)
+ .setTicker("Beiwe data collection running in the background, no action required")
+ .build()
+
+ // multiple sources recommend an ID of 1 because it works. documentation is very spotty about this
+ startForeground(1, notification)
+ foregroundServiceLastStarted = now
+ }
+
+ PersistentData.serviceStartCommand = Date(System.currentTimeMillis()).toLocaleString()
+
+ // onStartCommand is called every 30 seconds due to repeating high-priority-or-whatever
+ // alarms, so we will stick a core logic check here.
+ // printd("run_all_app_logic - onStartCommand")
+ run_all_app_logic()
+
+ // We want this service to continue running until it is explicitly stopped, so return sticky.
+ return START_STICKY
+ // in testing out this restarting behavior for the service it is entirely unclear if changing
+ // this return will have any observable effect despite the documentation's claim that it does.
+ // return START_REDELIVER_INTENT;
+ }
+
+ // the rest of these are ~identical
+ override fun onTaskRemoved(rootIntent: Intent?) {
+ // Log.d("BackroundService onTaskRemoved", "onTaskRemoved called with intent: " + rootIntent.toString() );
+ TextFileManager.writeDebugLogStatement("onTaskRemoved called with intent: $rootIntent")
+ PersistentData.serviceOnTaskRemoved = Date(System.currentTimeMillis()).toLocaleString()
+ restartService()
+ }
+
+ override fun onUnbind(intent: Intent?): Boolean {
+ // Log.d("BackroundService onUnbind", "onUnbind called with intent: " + intent.toString() );
+ TextFileManager.writeDebugLogStatement("onUnbind called with intent: $intent")
+ PersistentData.serviceOnUnbind = Date(System.currentTimeMillis()).toLocaleString()
+ restartService()
+ return super.onUnbind(intent)
+ }
+
+ override fun onDestroy() { // Log.w("BackgroundService", "BackgroundService was destroyed.");
+ // note: this does not run when the service is killed in a task manager, OR when the stopService() function is called from debugActivity.
+ TextFileManager.writeDebugLogStatement("BackgroundService was destroyed.")
+ PersistentData.serviceOnDestroy = Date(System.currentTimeMillis()).toLocaleString()
+ restartService()
+ super.onDestroy()
+ }
+
+ override fun onLowMemory() { // Log.w("BackroundService onLowMemory", "Low memory conditions encountered");
+ TextFileManager.writeDebugLogStatement("onLowMemory called.")
+ PersistentData.serviceOnLowMemory = Date(System.currentTimeMillis()).toLocaleString()
+ restartService()
+ }
+
+ override fun onTrimMemory(level: Int) {
+ // Log.w("BackroundService onTrimMemory", "Trim memory conditions encountered");
+ TextFileManager.writeDebugLogStatement("onTrimMemory called.")
+ PersistentData.serviceOnTrimMemory = Date(System.currentTimeMillis()).toLocaleString()
+ super.onTrimMemory(level)
+ }
+
+ /** Stops the BackgroundService instance, development tool */
+ fun stop() {
+ if (BuildConfig.APP_IS_BETA)
+ this.stopSelf()
+ }
+
+ /** Sets a timer that starts the service if it is not running after a half second. */
+ fun restartService() {
+ val restartServiceIntent = Intent(applicationContext, this.javaClass)
+ restartServiceIntent.setPackage(packageName)
+ val restartServicePendingIntent = PendingIntent.getService(
+ applicationContext,
+ 1,
+ restartServiceIntent,
+ pending_intent_flag_fix(PendingIntent.FLAG_ONE_SHOT)
+ )
+ // kotlin port action turned this into a very weird setter syntax using [] access...
+ (applicationContext.getSystemService(ALARM_SERVICE) as AlarmManager).set(
+ AlarmManager.ELAPSED_REALTIME,
+ SystemClock.elapsedRealtime() + 500,
+ restartServicePendingIntent
+ )
+ }
+
+ /** We sometimes need to restart the background service */
+ fun exit_and_restart_background_service() {
+ TextFileManager.writeDebugLogStatement("manually restarting background service")
+ // if this takes more than 500ms to restart, the app will ~crash... hmm. This is fine.
+ restartService()
+ System.exit(0)
+ }
+
+ // static assets
+ companion object {
+ // I guess we need access to this one in static contexts...
+ public var timer: Timer? = null
+
+ // localHandle is how static scopes access the currently instantiated main service.
+ // It is to be used ONLY to register new surveys with the running main service, because
+ // that code needs to be able to update the IntentFilters associated with timerReceiver.
+ // This is Really Hacky and terrible style, but it is okay because the scheduling code can only ever
+ // begin to run with an already fully instantiated main service.
+ var localHandle: MainService? = null
+
+ private var foregroundServiceLastStarted = 0L
+
+ // FIXME: in order to make this non-static we probably need to port PostReqeuest to kotlin
+ /** create timers that will trigger events throughout the program, and
+ * register the custom Intents with the controlMessageReceiver. */
+ @JvmStatic
+ fun registerTimers(applicationContext: Context) {
+ timer = Timer(localHandle!!)
+ val filter = IntentFilter()
+ filter.addAction(applicationContext.getString(R.string.turn_accelerometer_off))
+ filter.addAction(applicationContext.getString(R.string.turn_accelerometer_on))
+ filter.addAction(applicationContext.getString(R.string.turn_ambient_audio_off))
+ filter.addAction(applicationContext.getString(R.string.turn_ambient_audio_on))
+ filter.addAction(applicationContext.getString(R.string.turn_gyroscope_on))
+ filter.addAction(applicationContext.getString(R.string.turn_gyroscope_off))
+ filter.addAction(applicationContext.getString(R.string.turn_bluetooth_on))
+ filter.addAction(applicationContext.getString(R.string.turn_bluetooth_off))
+ filter.addAction(applicationContext.getString(R.string.turn_omniring_on))
+ filter.addAction(applicationContext.getString(R.string.turn_gps_on))
+ filter.addAction(applicationContext.getString(R.string.turn_gps_off))
+ filter.addAction(applicationContext.getString(R.string.signout_intent))
+ filter.addAction(applicationContext.getString(R.string.voice_recording))
+ filter.addAction(applicationContext.getString(R.string.run_wifi_log))
+ filter.addAction(applicationContext.getString(R.string.upload_data_files_intent))
+ filter.addAction(applicationContext.getString(R.string.create_new_data_files_intent))
+ filter.addAction(applicationContext.getString(R.string.check_for_new_surveys_intent))
+ filter.addAction(applicationContext.getString(R.string.check_for_sms_enabled))
+ filter.addAction(applicationContext.getString(R.string.check_for_call_log_enabled))
+ filter.addAction(applicationContext.getString(R.string.check_if_ambient_audio_recording_is_enabled))
+ filter.addAction(applicationContext.getString(R.string.fcm_upload))
+ filter.addAction(applicationContext.getString(R.string.check_for_new_device_settings_intent))
+ filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
+ filter.addAction("crashBeiwe")
+ filter.addAction("enterANR")
+
+ for (surveyId in PersistentData.getSurveyIds()) {
+ filter.addAction(surveyId)
+ }
+ applicationContext.registerReceiver(localHandle!!.timerReceiver, filter)
+ }
+
+ /**Refreshes the logout timer.
+ * This function has a THEORETICAL race condition, where the BackgroundService is not fully instantiated by a session activity,
+ * in this case we log an error to the debug log, print the error, and then wait for it to crash. In testing on a (much) older
+ * version of the app we would occasionally see the error message, but we have never (august 10 2015) actually seen the app crash
+ * inside this code. */
+ fun startAutomaticLogoutCountdownTimer() {
+ if (timer == null) {
+ Log.e("bacgroundService", "timer is null, BackgroundService may be about to crash, the Timer was null when the BackgroundService was supposed to be fully instantiated.")
+ TextFileManager.writeDebugLogStatement("our not-quite-race-condition encountered, Timer was null when the BackgroundService was supposed to be fully instantiated")
+ }
+ timer!!.setupExactSingleAlarm(PersistentData.getTimeBeforeAutoLogout(), Timer.signoutIntent)
+ PersistentData.loginOrRefreshLogin()
+ }
+
+ /** cancels the signout timer */
+ fun clearAutomaticLogoutCountdownTimer() {
+ timer!!.cancelAlarm(Timer.signoutIntent)
+ }
+
+ /** The Timer requires the BackgroundService in order to create alarms, hook into that functionality here. */
+ @JvmStatic
+ fun setSurveyAlarm(surveyId: String?, alarmTime: Calendar?) {
+ timer!!.startSurveyAlarm(surveyId!!, alarmTime!!)
+ }
+
+ @JvmStatic
+ fun cancelSurveyAlarm(surveyId: String?) {
+ timer!!.cancelAlarm(Intent(surveyId))
+ }
+ }
}
\ No newline at end of file
diff --git a/app/src/main/java/org/beiwe/app/PermissionHandler.kt b/app/src/main/java/org/beiwe/app/PermissionHandler.kt
index f6acca54..cc7ea35d 100644
--- a/app/src/main/java/org/beiwe/app/PermissionHandler.kt
+++ b/app/src/main/java/org/beiwe/app/PermissionHandler.kt
@@ -243,6 +243,11 @@ object PermissionHandler {
return PersistentData.getBluetoothEnabled() && checkBluetoothPermissions(context)
}
+ @JvmStatic
+ fun confirmOmniRing(context: Context): Boolean {
+ return PersistentData.getOmniRingEnabled() && checkBluetoothPermissions(context)
+ }
+
@JvmStatic
fun confirmAmbientAudioCollection(context: Context): Boolean {
return PersistentData.getAmbientAudioEnabled() && checkAccessRecordAudio(context)
@@ -264,7 +269,7 @@ object PermissionHandler {
if (!checkAccessCoarseLocation(context)) return Manifest.permission.ACCESS_COARSE_LOCATION
if (!checkAccessFineLocation(context)) return Manifest.permission.ACCESS_FINE_LOCATION
}
- if (PersistentData.getBluetoothEnabled()) {
+ if (PersistentData.getBluetoothEnabled() || PersistentData.getOmniRingEnabled()) {
// android versions below 12 use permission.BLUETOOTH and permission.BLUETOOTH_ADMIN,
// 12+ uses permission.BLUETOOTH_CONNECT and permission.BLUETOOTH_SCAN
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
@@ -361,6 +366,8 @@ object PermissionHandler {
permissions.put("most_recent_ambient_audio_stop", PersistentData.ambientAudioStop)
permissions.put("most_recent_bluetooth_start", PersistentData.bluetoothStart)
permissions.put("most_recent_bluetooth_stop", PersistentData.bluetoothStop)
+ permissions.put("most_recent_omniring_start", PersistentData.omniringStart)
+ permissions.put("most_recent_omniring_stop", PersistentData.omniringStop)
permissions.put("most_recent_gps_start", PersistentData.gpsStart)
permissions.put("most_recent_gps_stop", PersistentData.gpsStop)
permissions.put("most_recent_gyroscope_start", PersistentData.gyroscopeStart)
diff --git a/app/src/main/java/org/beiwe/app/Timer.kt b/app/src/main/java/org/beiwe/app/Timer.kt
index 033a0387..c7d2c2ec 100644
--- a/app/src/main/java/org/beiwe/app/Timer.kt
+++ b/app/src/main/java/org/beiwe/app/Timer.kt
@@ -33,6 +33,8 @@ class Timer(mainService: MainService) {
lateinit var gyroscopeOnIntent: Intent
lateinit var bluetoothOffIntent: Intent
lateinit var bluetoothOnIntent: Intent
+ lateinit var omniRingOffIntent: Intent
+ lateinit var omniRingOnIntent: Intent
lateinit var gpsOffIntent: Intent
lateinit var gpsOnIntent: Intent
@@ -77,6 +79,8 @@ class Timer(mainService: MainService) {
gyroscopeOnIntent = setupIntent(appContext.getString(R.string.turn_gyroscope_on))
bluetoothOffIntent = setupIntent(appContext.getString(R.string.turn_bluetooth_off))
bluetoothOnIntent = setupIntent(appContext.getString(R.string.turn_bluetooth_on))
+ omniRingOffIntent = setupIntent(appContext.getString(R.string.turn_omniring_off))
+ omniRingOnIntent = setupIntent(appContext.getString(R.string.turn_omniring_on))
gpsOffIntent = setupIntent(appContext.getString(R.string.turn_gps_off))
gpsOnIntent = setupIntent(appContext.getString(R.string.turn_gps_on))
diff --git a/app/src/main/java/org/beiwe/app/listeners/BluetoothListener.kt b/app/src/main/java/org/beiwe/app/listeners/BluetoothListener.kt
index 62464749..fdfcded2 100644
--- a/app/src/main/java/org/beiwe/app/listeners/BluetoothListener.kt
+++ b/app/src/main/java/org/beiwe/app/listeners/BluetoothListener.kt
@@ -6,7 +6,6 @@ import android.bluetooth.BluetoothAdapter.LeScanCallback
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
-import android.os.Build
import android.util.Log
import org.beiwe.app.storage.EncryptionEngine
import org.beiwe.app.storage.PersistentData
@@ -97,9 +96,9 @@ class BluetoothListener : BroadcastReceiver() {
// this check was incorrect for 13 months, however bonded devices are not the same as connected devices.
// This check was never relevent before (nobody ever noticed), so now we are just removing the check entirely.
// If we want to implement more bluetooth safety checks, see http://stackoverflow.com/questions/3932228/list-connected-bluetooth-devices
- // if ( bluetoothAdapter.getBondedDevices().isEmpty() ) {
- // Log.d("BluetoothListener", "found a bonded bluetooth device, will not be turning off bluetooth.");
- // externalBluetoothState = true; }
+ // if ( bluetoothAdapter.getBondedDevices().isEmpty() ) {
+ // Log.d("BluetoothListener", "found a bonded bluetooth device, will not be turning off bluetooth.");
+ // externalBluetoothState = true; }
if (!externalBluetoothState) { // if the outside world and us agree that it should be off, turn it off
bluetoothAdapter!!.disable()
@@ -159,7 +158,7 @@ class BluetoothListener : BroadcastReceiver() {
Log.i("BluetoothListener", "disable BLE scan.")
scanActive = false
bluetoothAdapter!!.stopLeScan(bluetoothCallback)
- disableBluetooth()
+// disableBluetooth()
}
/** Intelligently ACTUALLY STARTS a Bluetooth LE scan.
@@ -183,7 +182,8 @@ class BluetoothListener : BroadcastReceiver() {
@SuppressLint("NewApi")
private val bluetoothCallback = LeScanCallback { device, rssi, scanRecord ->
TextFileManager.getBluetoothLogFile().writeEncrypted(
- System.currentTimeMillis().toString() + "," + EncryptionEngine.hashMAC(device.toString()) + "," + rssi
+ System.currentTimeMillis()
+ .toString() + "," + EncryptionEngine.hashMAC(device.toString()) + "," + rssi
)
// Log.i("Bluetooth", System.currentTimeMillis() + "," + device.toString() + ", " + rssi )
}
diff --git a/app/src/main/java/org/beiwe/app/listeners/OmniringListener.kt b/app/src/main/java/org/beiwe/app/listeners/OmniringListener.kt
new file mode 100644
index 00000000..02381535
--- /dev/null
+++ b/app/src/main/java/org/beiwe/app/listeners/OmniringListener.kt
@@ -0,0 +1,268 @@
+package org.beiwe.app.listeners
+
+import android.app.Service
+import android.bluetooth.BluetoothAdapter
+import android.bluetooth.BluetoothDevice
+import android.bluetooth.BluetoothGatt
+import android.bluetooth.BluetoothGattCallback
+import android.bluetooth.BluetoothGattCharacteristic
+import android.bluetooth.BluetoothGattDescriptor
+import android.bluetooth.BluetoothGattService
+import android.bluetooth.BluetoothManager
+import android.bluetooth.BluetoothProfile
+import android.bluetooth.le.BluetoothLeScanner
+import android.bluetooth.le.ScanCallback
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.os.Binder
+import android.os.IBinder
+import android.util.Log
+import org.beiwe.app.PermissionHandler
+import org.beiwe.app.storage.TextFileManager
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+import java.util.UUID
+
+class OmniringListener : Service() {
+ private var bluetoothManager: BluetoothManager? = null
+ private var bluetoothAdapter: BluetoothAdapter? = null
+ private var bluetoothGatt: BluetoothGatt? = null
+ private var connectionState = STATE_DISCONNECTED
+ private var bluetoothLeScanner: BluetoothLeScanner? = null
+ private var omniringDevice: BluetoothDevice? = null
+ private var omniringDataCharacteristic: BluetoothGattCharacteristic? = null
+ private var lineCount = 0
+ var isOnState = false
+ var exists: Boolean = false
+
+ companion object {
+ private const val TAG = "OmniringListener"
+ private const val CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb"
+ private const val OMNIRING_DATA_CHARACTERISTIC_UUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"
+
+ private const val STATE_DISCONNECTED = 0
+ private const val STATE_CONNECTED = 2
+
+ @JvmField
+ var omniring_header =
+ "timestamp,PPG_red,PPG_IR,PPG_Green,IMU_Accel_x,IMU_Accel_y,IMU_Accel_z,IMU_Gyro_x,IMU_Gyro_y,IMU_Gyro_z,IMU_Mag_x,IMU_Mag_y,IMU_Mag_z,temperature,timestamp"
+
+ }
+
+ private val binder = LocalBinder()
+
+ inner class LocalBinder : Binder() {
+ // Return this instance of LocalService so clients can call public methods.
+ fun getService(): OmniringListener = this@OmniringListener
+ }
+
+ override fun onBind(intent: Intent?): IBinder? {
+ return binder
+ }
+
+ private fun unpackFByteArray(byteArray: ByteArray): Float {
+ val buffer = ByteBuffer.wrap(byteArray).order(ByteOrder.LITTLE_ENDIAN)
+ return buffer.float
+ }
+
+ private fun decodeByteData(byteData: ByteArray): List {
+ val floatArray = mutableListOf()
+ for (i in byteData.indices step 4) {
+ val tmpFloat = unpackFByteArray(byteData.copyOfRange(i, i + 4))
+ floatArray.add(tmpFloat)
+ }
+ return floatArray
+ }
+
+ private fun ByteArray.toHexString(): String = joinToString("") { "%02x".format(it) }
+
+ // Disable notificationsV
+ private fun disableNotification() = omniringDataCharacteristic?.let { characteristic ->
+ // Disable notifications
+ bluetoothGatt?.setCharacteristicNotification(characteristic, false)
+
+ // Configure the descriptor for notifications
+ val descriptor =
+ characteristic.getDescriptor(UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG))
+ descriptor.value = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE
+ bluetoothGatt?.writeDescriptor(descriptor)
+ }
+
+ // Enable notifications
+ private fun enableNotification() = omniringDataCharacteristic?.let { characteristic ->
+ // Enable notifications
+ bluetoothGatt?.setCharacteristicNotification(characteristic, true)
+
+ // Configure the descriptor for notifications
+ val descriptor =
+ characteristic.getDescriptor(UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG))
+ descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
+ bluetoothGatt?.writeDescriptor(descriptor)
+ }
+
+ private fun getSupportedGattServices(): List? {
+ return if (bluetoothGatt == null) null else bluetoothGatt?.services
+ }
+
+ private fun findOmniringCharacteristic() {
+ val gattServices = getSupportedGattServices()
+ gattServices?.forEach { service ->
+ Log.d(TAG, "subscribeToNotifications: service found ${service.uuid}")
+ service.characteristics.forEach { characteristic ->
+ Log.d(TAG, "subscribeToNotifications: characteristic found ${characteristic.uuid}")
+
+ if (characteristic.uuid.toString() == OMNIRING_DATA_CHARACTERISTIC_UUID) {
+ omniringDataCharacteristic = characteristic
+ Log.d(
+ TAG,
+ "subscribeToNotifications: omniring data characteristic found, enabling notifications"
+ )
+ if (isOnState) enableNotification() else disableNotification()
+ return
+ }
+ }
+ }
+ }
+
+ private val bluetoothGattCallback = object : BluetoothGattCallback() {
+ override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
+ super.onServicesDiscovered(gatt, status)
+ findOmniringCharacteristic()
+ }
+
+ override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
+ if (newState == BluetoothProfile.STATE_CONNECTED) {
+ Log.d(TAG, "onConnectionStateChange: connected to omniring ${gatt.device.name}")
+ Log.d(TAG, "onConnectionStateChange: now discovering services..")
+ connectionState = STATE_CONNECTED
+ bluetoothGatt?.discoverServices()
+ } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
+ Log.d(
+ TAG,
+ "onConnectionStateChange: disconnected from omniring ${gatt.device.name}"
+ )
+ connectionState = STATE_DISCONNECTED
+ }
+ }
+
+ override fun onCharacteristicChanged(
+ gatt: BluetoothGatt?,
+ characteristic: BluetoothGattCharacteristic?
+ ) {
+ if (lineCount > 1000) {
+ TextFileManager.getOmniRingLog().newFile()
+ lineCount = 0
+ }
+
+ val data = decodeByteData(characteristic?.value ?: byteArrayOf()).joinToString(",")
+ Log.d(TAG, "onCharacteristicChanged: $data")
+ TextFileManager.getOmniRingLog()
+ .writeEncrypted(System.currentTimeMillis().toString() + "," + data)
+ lineCount++
+ }
+
+ override fun onDescriptorWrite(
+ gatt: BluetoothGatt?,
+ descriptor: BluetoothGattDescriptor?,
+ status: Int
+ ) {
+ Log.d(TAG, "onDescriptorWrite: ${descriptor?.value?.toHexString()}")
+ }
+ }
+
+ private fun connect(address: String): Boolean {
+ bluetoothAdapter?.let { adapter ->
+ try {
+ val device = adapter.getRemoteDevice(address)
+ bluetoothGatt =
+ device.connectGatt(this@OmniringListener, false, bluetoothGattCallback)
+ return true
+ } catch (e: IllegalArgumentException) {
+ Log.e(TAG, "failed to connect to omniring ${e.message}")
+ return false
+ }
+ } ?: run {
+ Log.e(TAG, "connect: bluetooth adapter not initialized")
+ return false
+ }
+ }
+
+ private val scanCallback = object : ScanCallback() {
+ override fun onScanResult(callbackType: Int, result: android.bluetooth.le.ScanResult) {
+ super.onScanResult(callbackType, result)
+ if (omniringDevice != null && omniringDevice?.bondState == BluetoothAdapter.STATE_CONNECTED) {
+ return
+ }
+
+ val device = result.device
+ if (
+ PermissionHandler.checkBluetoothPermissions(this@OmniringListener) &&
+ device.name?.startsWith("OmniRing") == true // TODO: refactor this condition to be dynamically set by backend
+ ) {
+ omniringDevice = device
+ if (device.bondState != BluetoothAdapter.STATE_CONNECTED)
+ connect(device.address)
+ }
+ }
+
+ override fun onScanFailed(errorCode: Int) {
+ super.onScanFailed(errorCode)
+ Log.e(TAG, "Scan failed with error code: $errorCode")
+ }
+ }
+
+ private fun initialize(): Boolean {
+ Log.d(TAG, "initialize: init omniring")
+ bluetoothAdapter = bluetoothManager?.adapter
+ if (bluetoothAdapter == null) {
+ Log.e(TAG, "Unable to obtain a BluetoothAdapter.")
+ return false
+ }
+ bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner
+ return true
+ }
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ bluetoothManager = getSystemService(BLUETOOTH_SERVICE) as BluetoothManager
+ exists = packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
+ initialize()
+ return START_STICKY
+ }
+
+ val omniring_on_action: () -> Unit = {
+ Log.d(TAG, "omniring: on action called")
+ isOnState = true
+ if (bluetoothAdapter?.isEnabled == false) {
+ Log.e(TAG, "Bluetooth is disabled.")
+ } else {
+ if (omniringDevice == null) {
+ Log.d(TAG, "starting scan")
+ bluetoothLeScanner?.startScan(scanCallback)
+ } else if (connectionState == STATE_DISCONNECTED) {
+ connect(omniringDevice?.address ?: "")
+ } else if (omniringDataCharacteristic == null) {
+ findOmniringCharacteristic()
+ } else {
+ enableNotification()
+ }
+ }
+ }
+
+ val omniring_off_action: () -> Unit = {
+ isOnState = false
+ Log.d(TAG, "omniring: off action called")
+ disableNotification()
+ }
+
+ private fun close() {
+ bluetoothGatt?.let { gatt ->
+ gatt.close()
+ bluetoothGatt = null
+ }
+ }
+
+ override fun onDestroy() {
+ close()
+ super.onDestroy()
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/org/beiwe/app/storage/PersistentData.kt b/app/src/main/java/org/beiwe/app/storage/PersistentData.kt
index 283c6b43..408bfcc4 100644
--- a/app/src/main/java/org/beiwe/app/storage/PersistentData.kt
+++ b/app/src/main/java/org/beiwe/app/storage/PersistentData.kt
@@ -34,6 +34,7 @@ const val CALLS_ENABLED = "calls"
const val TEXTS_ENABLED = "texts"
const val WIFI_ENABLED = "wifi"
const val BLUETOOTH_ENABLED = "bluetooth"
+const val OMNIRING_ENABLED = "omniring"
const val POWER_STATE_ENABLED = "power_state"
const val AMBIENT_AUDIO_ENABLED = "ambient_audio"
const val ALLOW_UPLOAD_OVER_CELLULAR_DATA = "allow_upload_over_cellular_data"
@@ -52,6 +53,8 @@ const val GYROSCOPE_FREQUENCY = "gyro_frequency"
const val BLUETOOTH_ON_SECONDS = "bluetooth_on_duration_seconds"
const val BLUETOOTH_TOTAL_SECONDS = "bluetooth_total_duration_seconds"
const val BLUETOOTH_GLOBAL_OFFSET_SECONDS = "bluetooth_global_offset_seconds"
+const val OMNIRING_OFF_SECONDS = "omniring_off_duration_seconds"
+const val OMNIRING_ON_SECONDS = "omniring_on_duration_seconds"
const val CHECK_FOR_NEW_SURVEYS_FREQUENCY_SECONDS = "check_for_new_surveys_frequency_seconds"
const val CREATE_NEW_DATA_FILES_FREQUENCY_SECONDS = "create_new_data_files_frequency_seconds"
const val GPS_OFF_SECONDS = "gps_off_duration_seconds"
@@ -99,6 +102,8 @@ const val MOST_RECENT_AMBIENT_AUDIO_START = "most_recent_ambient_audio_start"
const val MOST_RECENT_AMBIENT_AUDIO_STOP = "most_recent_ambient_audio_stop"
const val MOST_RECENT_BLUETOOTH_START = "most_recent_bluetooth_start"
const val MOST_RECENT_BLUETOOTH_STOP = "most_recent_bluetooth_stop"
+const val MOST_RECENT_OMNIRING_START = "most_recent_omniring_start"
+const val MOST_RECENT_OMNIRING_STOP = "most_recent_omniring_stop"
const val MOST_RECENT_GPS_START = "most_recent_gps_start"
const val MOST_RECENT_GPS_STOP = "most_recent_gps_stop"
const val MOST_RECENT_GYROSCOPE_START = "most_recent_gyroscope_start"
@@ -185,8 +190,15 @@ object PersistentData {
// IS_REGISTERED
@JvmStatic fun getIsRegistered(): Boolean { return pref.getBoolean(IS_REGISTERED, false) }
@JvmStatic fun setIsRegistered(value: Boolean) { putCommit(IS_REGISTERED, value) }
- @JvmStatic fun setLastRequestedPermission(value: String) { putCommit(LAST_REQUESTED_PERMISSION, value) }
- @JvmStatic fun getLastRequestedPermission(): String { return pref.getString(LAST_REQUESTED_PERMISSION, "")?: "" }
+ @JvmStatic
+ fun setLastRequestedPermission(value: String) {
+ putCommit(LAST_REQUESTED_PERMISSION, value)
+ }
+
+ @JvmStatic
+ fun getLastRequestedPermission(): String {
+ return pref.getString(LAST_REQUESTED_PERMISSION, "") ?: ""
+ }
@JvmStatic fun getTakingSurvey(): Boolean { return pref.getBoolean(IS_TAKING_SURVEY, false) }
@JvmStatic fun setTakingSurvey() { putCommit(IS_TAKING_SURVEY, true) }
@JvmStatic fun setNotTakingSurvey() { putCommit(IS_TAKING_SURVEY, false) }
@@ -221,8 +233,9 @@ object PersistentData {
@JvmStatic var appOnServiceStart: String
get() = pref.getString(MOST_RECENT_SERVICE_START, "")?: ""
set(value) = putCommit(MOST_RECENT_SERVICE_START, value)
- @JvmStatic var appOnServiceStartFirstRun: String
- get() = pref.getString(MOST_RECENT_SERVICE_START_FIRST_RUN, "")?: ""
+ @JvmStatic
+ var appOnServiceStartFirstRun: String
+ get() = pref.getString(MOST_RECENT_SERVICE_START_FIRST_RUN, "") ?: ""
set(value) = putCommit(MOST_RECENT_SERVICE_START_FIRST_RUN, value)
// app activity recent events
@@ -261,6 +274,14 @@ object PersistentData {
@JvmStatic var bluetoothStop: String
get() = pref.getString(MOST_RECENT_BLUETOOTH_STOP, "")?: ""
set(value) = putCommit(MOST_RECENT_BLUETOOTH_STOP, value)
+ @JvmStatic
+ var omniringStart: String
+ get() = pref.getString(MOST_RECENT_OMNIRING_START, "") ?: ""
+ set(value) = putCommit(MOST_RECENT_OMNIRING_START, value)
+ @JvmStatic
+ var omniringStop: String
+ get() = pref.getString(MOST_RECENT_OMNIRING_STOP, "") ?: ""
+ set(value) = putCommit(MOST_RECENT_OMNIRING_STOP, value)
@JvmStatic var gpsStart: String
get() = pref.getString(MOST_RECENT_GPS_START, "")?: ""
set(value) = putCommit(MOST_RECENT_GPS_START, value)
@@ -273,11 +294,13 @@ object PersistentData {
@JvmStatic var gyroscopeStop: String
get() = pref.getString(MOST_RECENT_GYROSCOPE_STOP, "")?: ""
set(value) = putCommit(MOST_RECENT_GYROSCOPE_STOP, value)
- @JvmStatic var appUploadAttempt: String
- get() = pref.getString(MOST_RECENT_UPLOAD_ATTEMPT, "")?: ""
+ @JvmStatic
+ var appUploadAttempt: String
+ get() = pref.getString(MOST_RECENT_UPLOAD_ATTEMPT, "") ?: ""
set(value) = putCommit(MOST_RECENT_UPLOAD_ATTEMPT, value)
- @JvmStatic var appUploadStart: String
- get() = pref.getString(MOST_RECENT_UPLOAD_START, "")?: ""
+ @JvmStatic
+ var appUploadStart: String
+ get() = pref.getString(MOST_RECENT_UPLOAD_START, "") ?: ""
set(value) = putCommit(MOST_RECENT_UPLOAD_START, value)
@JvmStatic var registrationPhoneNumberEverPrompted: Boolean
@@ -318,8 +341,24 @@ object PersistentData {
@JvmStatic fun setAmbientAudioCollectionIsEnabled(enabled: Boolean): Boolean { return putCommit(AMBIENT_AUDIO_ENABLED, enabled) }
@JvmStatic fun getBluetoothEnabled(): Boolean { return pref.getBoolean(BLUETOOTH_ENABLED, false) }
@JvmStatic fun setBluetoothEnabled(enabled: Boolean): Boolean { return putCommit(BLUETOOTH_ENABLED, enabled) }
- @JvmStatic fun getCallLoggingEnabled(): Boolean { return pref.getBoolean(CALLS_ENABLED, false) }
- @JvmStatic fun setCallLoggingEnabled(enabled: Boolean): Boolean { return putCommit(CALLS_ENABLED, enabled) }
+ @JvmStatic
+ fun getOmniRingEnabled(): Boolean {
+ return pref.getBoolean(OMNIRING_ENABLED, false)
+ }
+
+ @JvmStatic
+ fun setOmniRingEnabled(enabled: Boolean): Boolean {
+ return putCommit(OMNIRING_ENABLED, enabled)
+ }
+ @JvmStatic
+ fun getCallLoggingEnabled(): Boolean {
+ return pref.getBoolean(CALLS_ENABLED, false)
+ }
+
+ @JvmStatic
+ fun setCallLoggingEnabled(enabled: Boolean): Boolean {
+ return putCommit(CALLS_ENABLED, enabled)
+ }
@JvmStatic fun getGpsEnabled(): Boolean { return pref.getBoolean(GPS_ENABLED, false) }
@JvmStatic fun setGpsEnabled(enabled: Boolean): Boolean { return putCommit(GPS_ENABLED, enabled) }
@JvmStatic fun getGyroscopeEnabled(): Boolean { return pref.getBoolean(GYROSCOPE_ENABLED, false) }
@@ -355,6 +394,10 @@ object PersistentData {
@JvmStatic fun setBluetoothOnDuration(seconds: Long) { putCommit(BLUETOOTH_ON_SECONDS, seconds) }
@JvmStatic fun getBluetoothTotalDuration(): Long { return 1000L * pref.getLong(BLUETOOTH_TOTAL_SECONDS, (5 * 60).toLong()) }
@JvmStatic fun setBluetoothTotalDuration(seconds: Long) { putCommit(BLUETOOTH_TOTAL_SECONDS, seconds) }
+ @JvmStatic fun getOmniRingOffDuration(): Long { return 1000L * pref.getLong(OMNIRING_OFF_SECONDS, 10) }
+ @JvmStatic fun setOmniRingOffDuration(seconds: Long) { putCommit(OMNIRING_OFF_SECONDS, seconds) }
+ @JvmStatic fun getOmniRingOnDuration(): Long { return 1000L * pref.getLong(OMNIRING_ON_SECONDS, (10 * 60).toLong()) }
+ @JvmStatic fun setOmniRingOnDuration(seconds: Long) { putCommit(OMNIRING_ON_SECONDS, seconds) }
@JvmStatic fun getCheckForNewSurveysFrequency(): Long { return 1000L * pref.getLong(CHECK_FOR_NEW_SURVEYS_FREQUENCY_SECONDS, (24 * 60 * 60).toLong()) }
@JvmStatic fun setCheckForNewSurveysFrequency(seconds: Long) { putCommit(CHECK_FOR_NEW_SURVEYS_FREQUENCY_SECONDS, seconds) }
@JvmStatic fun getCreateNewDataFilesFrequency(): Long { return 1000L * pref.getLong(CREATE_NEW_DATA_FILES_FREQUENCY_SECONDS, (15 * 60).toLong()) }
@@ -384,7 +427,6 @@ object PersistentData {
// we want default to be 0 so that checks "is this value less than the current expected value" (eg "did this timer event pass already")
-
/*###########################################################################################
################################### Text Strings ############################################
###########################################################################################*/
diff --git a/app/src/main/java/org/beiwe/app/storage/SetDeviceSettings.kt b/app/src/main/java/org/beiwe/app/storage/SetDeviceSettings.kt
index ae875c75..4905160c 100644
--- a/app/src/main/java/org/beiwe/app/storage/SetDeviceSettings.kt
+++ b/app/src/main/java/org/beiwe/app/storage/SetDeviceSettings.kt
@@ -21,6 +21,8 @@ object SetDeviceSettings {
enablement_change = enablement_change or PersistentData.setTextsEnabled(deviceSettings.getBoolean("texts"))
PersistentData.setWifiEnabled(deviceSettings.getBoolean("wifi")) // wifi doesn't have any active state, can ignore.
enablement_change = enablement_change or PersistentData.setBluetoothEnabled(deviceSettings.getBoolean("bluetooth"))
+ enablement_change =
+ enablement_change or PersistentData.setOmniRingEnabled(deviceSettings.getBoolean("omniring"))
enablement_change = enablement_change or PersistentData.setPowerStateEnabled(deviceSettings.getBoolean("power_state"))
// any sections in try-catch blocks were added after go-live, so must be caught in case the
// app is newer than the server backend.
@@ -50,6 +52,8 @@ object SetDeviceSettings {
PersistentData.setBluetoothOnDuration(deviceSettings.getLong("bluetooth_on_duration_seconds"))
PersistentData.setBluetoothTotalDuration(deviceSettings.getLong("bluetooth_total_duration_seconds"))
PersistentData.setBluetoothGlobalOffset(deviceSettings.getLong("bluetooth_global_offset_seconds"))
+ PersistentData.setOmniRingOffDuration(deviceSettings.getLong("omniring_off_duration_seconds"))
+ PersistentData.setOmniRingOnDuration(deviceSettings.getLong("omniring_on_duration_seconds"))
PersistentData.setCheckForNewSurveysFrequency(deviceSettings.getLong("check_for_new_surveys_frequency_seconds"))
PersistentData.setCreateNewDataFilesFrequency(deviceSettings.getLong("create_new_data_files_frequency_seconds"))
PersistentData.setGpsOffDuration(deviceSettings.getLong("gps_off_duration_seconds"))
diff --git a/app/src/main/java/org/beiwe/app/storage/TextFileManager.java b/app/src/main/java/org/beiwe/app/storage/TextFileManager.java
index 0c06687b..36360e54 100644
--- a/app/src/main/java/org/beiwe/app/storage/TextFileManager.java
+++ b/app/src/main/java/org/beiwe/app/storage/TextFileManager.java
@@ -13,6 +13,7 @@
import org.beiwe.app.listeners.CallLogger;
import org.beiwe.app.listeners.GPSListener;
import org.beiwe.app.listeners.GyroscopeListener;
+import org.beiwe.app.listeners.OmniringListener;
import org.beiwe.app.listeners.PowerStateListener;
import org.beiwe.app.listeners.SmsSentLogger;
import org.beiwe.app.listeners.WifiListener;
@@ -58,8 +59,9 @@ public class TextFileManager {
private static TextFileManager callLog;
private static TextFileManager textsLog;
private static TextFileManager bluetoothLog;
+ private static TextFileManager omniRingLog;
private static TextFileManager debugLogFile;
-
+
private static TextFileManager surveyTimings;
private static TextFileManager surveyAnswers;
private static TextFileManager wifiLog;
@@ -117,6 +119,11 @@ public static TextFileManager getBluetoothLogFile () {
checkAvailableWithTimeout("bluetoothLog");
return bluetoothLog;
}
+
+ public static TextFileManager getOmniRingLog() {
+ checkAvailableWithTimeout("omniRingLog");
+ return omniRingLog;
+ }
public static TextFileManager getWifiLogFile () {
checkAvailableWithTimeout("wifiLog");
@@ -182,6 +189,9 @@ private static Boolean checkTextFileAvailable (String thing) {
if (thing.equals("bluetoothLog")) {
return (bluetoothLog != null);
}
+ if (thing.equals("omniRingLog")) {
+ return (omniRingLog != null);
+ }
if (thing.equals("wifiLog")) {
return (wifiLog != null);
}
@@ -274,6 +284,9 @@ public static synchronized void initialize (Context appContext) {
bluetoothLog = new TextFileManager(
appContext, "bluetoothLog", BluetoothListener.header, false, false, true, !PersistentData.getBluetoothEnabled()
);
+ omniRingLog = new TextFileManager(
+ appContext, "omniRingLog", OmniringListener.omniring_header, false, false, true, !PersistentData.getOmniRingEnabled()
+ );
// Files created on specific events/written to in one go.
surveyTimings = new TextFileManager(
appContext, "surveyTimings_", SurveyTimingsRecorder.header, false, false, true, false
@@ -559,6 +572,7 @@ public static synchronized void makeNewFilesForEverything () {
callLog.newFile();
textsLog.newFile();
bluetoothLog.newFile();
+ omniRingLog.newFile();
debugLogFile.newFile();
}
@@ -605,6 +619,7 @@ public static synchronized String[] getAllUploadableFiles () {
files.remove(TextFileManager.getTextsLogFile().fileName);
files.remove(TextFileManager.getDebugLogFile().fileName);
files.remove(TextFileManager.getBluetoothLogFile().fileName);
+ files.remove(TextFileManager.getOmniRingLog().fileName);
files.remove(AmbientAudioListener.currentlyWritingEncryptedFilename);
// These files are only occasionally open, but they may be currently open. If they are, don't upload them
diff --git a/app/src/main/java/org/beiwe/app/utils.kt b/app/src/main/java/org/beiwe/app/utils.kt
index f556da83..e7ff12f7 100644
--- a/app/src/main/java/org/beiwe/app/utils.kt
+++ b/app/src/main/java/org/beiwe/app/utils.kt
@@ -3,8 +3,12 @@ package org.beiwe.app
import android.app.PendingIntent
import android.content.Context
import android.content.res.Configuration
+import android.icu.text.SimpleDateFormat
+import android.icu.util.TimeZone
import android.os.Build
import android.util.Log
+import java.util.Date
+import java.util.Locale
// This file is a location for new static functions, further factoring into files will occur when length of file becomes a problem.
@@ -69,4 +73,14 @@ fun is_nightmode(appContext: Context): Boolean {
return false
}
return false
+}
+
+/**
+ * Converts a UTC timestamp to a human-readable date and time string, based on current device's timezone.
+ */
+fun convertTimestamp(utcTimestamp: Long): String {
+ val date = Date(utcTimestamp)
+ val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
+ dateFormat.timeZone = TimeZone.getDefault()
+ return dateFormat.format(date)
}
\ No newline at end of file
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 85692bcd..72074215 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -194,6 +194,8 @@
Gyroscope On
Bluetooth OFF
Bluetooth On
+ Omniring OFF
+ Omniring On
GPS OFF
GPS On
Signout
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
index 13372aef..2c352119 100644
Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradlew b/gradlew
index 9d82f789..f5feea6d 100755
--- a/gradlew
+++ b/gradlew
@@ -1,74 +1,130 @@
-#!/usr/bin/env bash
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
##############################################################################
-##
-## Gradle start up script for UN*X
-##
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
##############################################################################
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
-APP_NAME="Gradle"
-APP_BASE_NAME=`basename "$0"`
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
+' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD="maximum"
+MAX_FD=maximum
-warn ( ) {
+warn () {
echo "$*"
-}
+} >&2
-die ( ) {
+die () {
echo
echo "$*"
echo
exit 1
-}
+} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
-case "`uname`" in
- CYGWIN* )
- cygwin=true
- ;;
- Darwin* )
- darwin=true
- ;;
- MINGW* )
- msys=true
- ;;
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
esac
-# Attempt to set APP_HOME
-# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG=`dirname "$PRG"`"/$link"
- fi
-done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >/dev/null
-APP_HOME="`pwd -P`"
-cd "$SAVED" >/dev/null
-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
- JAVACMD="$JAVA_HOME/jre/sh/java"
+ JAVACMD=$JAVA_HOME/jre/sh/java
else
- JAVACMD="$JAVA_HOME/bin/java"
+ JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -77,84 +133,120 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
- JAVACMD="java"
- which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+ JAVACMD=java
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
+ fi
fi
# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
- MAX_FD_LIMIT=`ulimit -H -n`
- if [ $? -eq 0 ] ; then
- if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
- MAX_FD="$MAX_FD_LIMIT"
- fi
- ulimit -n $MAX_FD
- if [ $? -ne 0 ] ; then
- warn "Could not set maximum file descriptor limit: $MAX_FD"
- fi
- else
- warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
- fi
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
fi
-# For Darwin, add options to specify how the application appears in the dock
-if $darwin; then
- GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
-fi
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin ; then
- APP_HOME=`cygpath --path --mixed "$APP_HOME"`
- CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
- JAVACMD=`cygpath --unix "$JAVACMD"`
-
- # We build the pattern for arguments to be converted via cygpath
- ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
- SEP=""
- for dir in $ROOTDIRSRAW ; do
- ROOTDIRS="$ROOTDIRS$SEP$dir"
- SEP="|"
- done
- OURCYGPATTERN="(^($ROOTDIRS))"
- # Add a user-defined pattern to the cygpath arguments
- if [ "$GRADLE_CYGPATTERN" != "" ] ; then
- OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
- fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
- i=0
- for arg in "$@" ; do
- CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
- CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
-
- if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
- eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
- else
- eval `echo args$i`="\"$arg\""
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
fi
- i=$((i+1))
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
done
- case $i in
- (0) set -- ;;
- (1) set -- "$args0" ;;
- (2) set -- "$args0" "$args1" ;;
- (3) set -- "$args0" "$args1" "$args2" ;;
- (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
- (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
- (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
- (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
- (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
- (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
- esac
fi
-# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
-function splitJvmOpts() {
- JVM_OPTS=("$@")
-}
-eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
-JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
-exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/gradlew.bat b/gradlew.bat
index aec99730..9b42019c 100644
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -1,4 +1,22 @@
-@if "%DEBUG%" == "" @echo off
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@@ -8,26 +26,30 @@
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS=
-
set DIRNAME=%~dp0
-if "%DIRNAME%" == "" set DIRNAME=.
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
-if "%ERRORLEVEL%" == "0" goto init
+if %ERRORLEVEL% equ 0 goto execute
-echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
goto fail
@@ -35,54 +57,36 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-if exist "%JAVA_EXE%" goto init
+if exist "%JAVA_EXE%" goto execute
-echo.
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
goto fail
-:init
-@rem Get command-line arguments, handling Windowz variants
-
-if not "%OS%" == "Windows_NT" goto win9xME_args
-if "%@eval[2+2]" == "4" goto 4NT_args
-
-:win9xME_args
-@rem Slurp the command line arguments.
-set CMD_LINE_ARGS=
-set _SKIP=2
-
-:win9xME_args_slurp
-if "x%~1" == "x" goto execute
-
-set CMD_LINE_ARGS=%*
-goto execute
-
-:4NT_args
-@rem Get arguments from the 4NT Shell from JP Software
-set CMD_LINE_ARGS=%$
-
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
-if "%ERRORLEVEL%"=="0" goto mainEnd
+if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
-if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
-exit /b 1
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal