diff --git a/composeApp/src/androidMain/AndroidManifest.xml b/composeApp/src/androidMain/AndroidManifest.xml index e5195320..2d6b97b8 100644 --- a/composeApp/src/androidMain/AndroidManifest.xml +++ b/composeApp/src/androidMain/AndroidManifest.xml @@ -8,6 +8,12 @@ first launch. docs/notifications-and-background-sync.md, Phase 6. --> + + + + @@ -30,6 +36,14 @@ + + + \ No newline at end of file diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt index f0dd2823..816f7bb3 100644 --- a/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt @@ -6,6 +6,8 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.navigation.compose.rememberNavController +import mobi.giza.android.background.StayConnectedService +import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.GizaApp import mobi.giza.compose.notifications.NotificationTaps @@ -21,6 +23,12 @@ class MainActivity : ComponentActivity() { tapped(intent) + // From here, in front, because Android will not start a foreground service from the + // background: a reboot or a killed process brings it back on the next launch. + if (ExperimentalFeatures.backgroundSync && StayConnectedService.isOn(this)) { + StayConnectedService.start(this) + } + setContent { val navController = rememberNavController() diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/background/StayConnectedService.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/background/StayConnectedService.kt new file mode 100644 index 00000000..883b32d6 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/background/StayConnectedService.kt @@ -0,0 +1,131 @@ +package mobi.giza.android.background + +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.IBinder +import androidx.core.app.NotificationCompat +import androidx.core.app.ServiceCompat +import androidx.core.content.ContextCompat +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import mobi.giza.android.GizaApplication +import mobi.giza.android.MainActivity +import mobi.giza.android.R +import mobi.giza.compose.AppLifecycle +import mobi.giza.compose.identity.DefaultIdentity +import mobi.giza.compose.identity.Identity +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.stay_connected_channel +import mobi.giza.compose.resources.stay_connected_notification +import org.jetbrains.compose.resources.getString + +/** + * Stay connected: the live subscriptions, held open while the app is closed, for as long as the + * user leaves this on. docs/notifications-and-background-sync.md, D10 and Phase 10. + * + * It starts nothing of its own. It keeps `AppLifecycle.holdConnections` true, and if no screen has + * set an identity it activates the default profile in the runtime, as the background pass does -- + * after which the app's own engines are what run. + */ +class StayConnectedService : Service() { + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + @Volatile + private var activatedHere: Identity? = null + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + ServiceCompat.startForeground( + this, + NOTIFICATION_ID, + notification(), + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE else 0, + ) + AppLifecycle.keepConnected(AppLifecycle.KEEP_STAY_CONNECTED) + + val runtime = (application as GizaApplication).runtime + scope.launch { + runtime.synchronization + runtime.notary + runtime.notifications + if (runtime.activeIdentity.value == null) { + DefaultIdentity.load(runtime.phoenixGlobal)?.let { identity -> + activatedHere = identity + runtime.activeIdentity.compareAndSet(null, identity) + } + } + } + return START_STICKY + } + + override fun onDestroy() { + AppLifecycle.release(AppLifecycle.KEEP_STAY_CONNECTED) + val runtime = (application as GizaApplication).runtime + activatedHere?.let { identity -> + if (!AppLifecycle.isVisible.value) runtime.activeIdentity.compareAndSet(identity, null) + } + scope.cancel() + super.onDestroy() + } + + private fun notification(): android.app.Notification { + // Read once, here, before startForeground's deadline; a resource read is not slow. + val (channelName, text) = runBlocking { + getString(Res.string.stay_connected_channel) to getString(Res.string.stay_connected_notification) + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + getSystemService(NotificationManager::class.java)?.createNotificationChannel( + NotificationChannel(CHANNEL, channelName, NotificationManager.IMPORTANCE_MIN) + ) + } + val open = PendingIntent.getActivity( + this, 0, Intent(this, MainActivity::class.java), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + return NotificationCompat.Builder(this, CHANNEL) + .setSmallIcon(R.drawable.ic_launcher_monochrome) + .setContentTitle(getString(R.string.app_name)) + .setContentText(text) + .setPriority(NotificationCompat.PRIORITY_MIN) + .setOngoing(true) + .setContentIntent(open) + .build() + } + + companion object { + private const val CHANNEL = "connection" + private const val NOTIFICATION_ID = 2 + private const val PREFERENCES = "giza_background" + private const val KEY_STAY_CONNECTED = "stay_connected" + + /** Whether the user turned it on. A device's choice, not a profile's. */ + fun isOn(context: Context): Boolean = + context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE).getBoolean(KEY_STAY_CONNECTED, false) + + fun set(context: Context, on: Boolean) { + context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE).edit().putBoolean(KEY_STAY_CONNECTED, on).apply() + if (on) start(context) else stop(context) + } + + /** From the foreground only: Android refuses a foreground service started from the background. */ + fun start(context: Context) { + ContextCompat.startForegroundService(context, Intent(context, StayConnectedService::class.java)) + } + + fun stop(context: Context) { + context.stopService(Intent(context, StayConnectedService::class.java)) + } + } +} diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt index 00b6c174..30c236d7 100644 --- a/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt +++ b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/BackgroundSyncSection.android.kt @@ -3,8 +3,17 @@ package mobi.giza.compose.notifications import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalContext +import mobi.giza.android.background.StayConnectedService import mobi.giza.compose.resources.Res import mobi.giza.compose.resources.background_android_explanation +import mobi.giza.compose.resources.stay_connected +import mobi.giza.compose.resources.stay_connected_supporting +import mobi.giza.compose.ui.composable.SwitchRow import org.jetbrains.compose.resources.stringResource @Composable @@ -12,5 +21,18 @@ actual fun PlatformBackgroundExplanation() { Text(stringResource(Res.string.background_android_explanation), style = MaterialTheme.typography.bodyMedium) } +/** Stay connected, which only Android offers: the others either cannot or need not. Phase 10. */ @Composable -actual fun PlatformBackgroundSettings() = Unit +actual fun PlatformBackgroundSettings() { + val context = LocalContext.current + var on by remember { mutableStateOf(StayConnectedService.isOn(context)) } + SwitchRow( + headline = stringResource(Res.string.stay_connected), + supporting = stringResource(Res.string.stay_connected_supporting), + checked = on, + enabled = true, + ) { checked -> + on = checked + StayConnectedService.set(context.applicationContext, checked) + } +} diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 553062f5..b262a0cd 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -827,4 +827,8 @@ While Giza is closed, iOS decides when it may check for messages: sometimes within minutes, sometimes a few times a day, and not at all after Giza is swiped away. Background App Refresh is off for Giza, so it cannot check for messages while closed. You can turn it on in the Settings app. Giza checks for messages while it is running, minimised or not. Closed, it checks nothing. + Stay connected + Messages arrive within seconds. Android shows a notification for as long as it is on, and the battery runs down faster. + Connection + Connected for new messages