Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,15 @@ class MainActivity : FlutterActivity() {
result.success(null)
}

"getSmartRouteReminderLog" -> {
result.success(SmartRouteNotificationSupport.loadReminderLog(this))
}

"forgetSmartRouteReminders" -> {
SmartRouteNotificationSupport.forgetReminders(this)
result.success(null)
}

"setApplicationInForeground" -> {
val appInForeground = call.argument<Boolean>("appInForeground") ?: false
AppRuntimeStateStore.setAppInForeground(this, appInForeground)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,80 +7,72 @@ import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import java.util.concurrent.TimeUnit
import org.json.JSONArray
import org.json.JSONObject

object SmartRouteNotificationScheduler {
private const val WORK_NAME = "smart_route_notification_refresh"
private const val MIN_TOTAL_OPENS_FOR_RECOMMENDATION = 3
private const val FLUTTER_PREFERENCES_NAME = "FlutterSharedPreferences"
private const val SETTINGS_KEY = "flutter.app_settings"
private const val SETTINGS_FALLBACK_KEY = "app_settings"
private const val ROUTE_USAGE_KEY = "flutter.route_usage_profiles"
private const val ROUTE_USAGE_FALLBACK_KEY = "route_usage_profiles"
private const val SETTINGS_NOTIFICATIONS_ENABLED_KEY = "enableSmartRouteNotifications"
/** The name the work is scheduled under. */
internal const val WORK_NAME = "smart_route_notification_refresh"

fun sync(context: Context, enabled: Boolean) {
val workManager = WorkManager.getInstance(context)
if (!enabled || !hasLearnedRoutes(context)) {
workManager.cancelUniqueWork(WORK_NAME)
return
}

val request = PeriodicWorkRequestBuilder<SmartRouteNotificationWorker>(
15,
TimeUnit.MINUTES,
).setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build(),
).build()
/**
* Held while the plan is read and the work scheduled or cancelled to
* match it, by the app and by the background check alike.
*
* The app writes a plan and only then asks for the work to be synced, so
* a decision taken under this lock from a plan that has since been
* replaced is always followed by one taken from the new plan, and
* WorkManager carries both out in the order they were asked for. Without
* it, a check that read the old plan could cancel the work after the app
* had rescheduled it for the new one.
*/
private val lock = Any()

workManager.enqueueUniquePeriodicWork(
WORK_NAME,
ExistingPeriodicWorkPolicy.UPDATE,
request,
)
}
/**
* Runs the background check only while there is something for it to do:
* the setting is on and the plan still holds a habit that has not lapsed.
*/
fun sync(context: Context, enabled: Boolean) {
synchronized(lock) {
val plan = if (enabled) SmartRouteNotificationSupport.loadPlan(context) else null
if (plan == null ||
!SmartRouteReminderRules.hasLiveSlots(plan, System.currentTimeMillis())
) {
cancelUnlocked(context)
return
}

fun syncFromPreferences(context: Context) {
sync(context, loadEnabledFromPreferences(context))
}
val request = PeriodicWorkRequestBuilder<SmartRouteNotificationWorker>(
15,
TimeUnit.MINUTES,
).setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build(),
).build()

private fun loadEnabledFromPreferences(context: Context): Boolean {
val preferences = context.getSharedPreferences(
FLUTTER_PREFERENCES_NAME,
Context.MODE_PRIVATE,
)
val raw = preferences.getString(SETTINGS_KEY, null)
?: preferences.getString(SETTINGS_FALLBACK_KEY, null)
?: return false
return try {
JSONObject(raw).optBoolean(SETTINGS_NOTIFICATIONS_ENABLED_KEY, false)
} catch (_: Exception) {
false
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
WORK_NAME,
ExistingPeriodicWorkPolicy.UPDATE,
request,
)
}
}

private fun hasLearnedRoutes(context: Context): Boolean {
val preferences = context.getSharedPreferences(
FLUTTER_PREFERENCES_NAME,
Context.MODE_PRIVATE,
)
val raw = preferences.getString(ROUTE_USAGE_KEY, null)
?: preferences.getString(ROUTE_USAGE_FALLBACK_KEY, null)
?: return false
return try {
val profiles = JSONArray(raw)
for (index in 0 until profiles.length()) {
val item = profiles.optJSONObject(index) ?: continue
if (item.optInt("totalOpens", 0) >= MIN_TOTAL_OPENS_FOR_RECOMMENDATION) {
return true
}
/**
* Stops the background check if the plan as it is now has nothing left
* that could fire — not the plan the caller read some time ago, which the
* app may have replaced since with one that does.
*/
fun cancelIfNothingLive(context: Context) {
synchronized(lock) {
val plan = SmartRouteNotificationSupport.loadPlan(context)
if (plan == null ||
!SmartRouteReminderRules.hasLiveSlots(plan, System.currentTimeMillis())
) {
cancelUnlocked(context)
}
false
} catch (_: Exception) {
false
}
}

private fun cancelUnlocked(context: Context) {
WorkManager.getInstance(context).cancelUniqueWork(WORK_NAME)
}
}
Loading