-
Notifications
You must be signed in to change notification settings - Fork 19
Demo: Add example using a foreground service for synchronization #143
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
676622e
Adopt Koin for dependency injection
simolus3 b808c1b
Add background sync example
simolus3 e07e987
Avoid starting sync service twice
simolus3 9bbc084
Document how foreground services are set up
simolus3 9991199
Fix typo
simolus3 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
/build |
59 changes: 59 additions & 0 deletions
59
demos/supabase-todolist/androidBackgroundSync/build.gradle.kts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
plugins { | ||
alias(libs.plugins.androidApplication) | ||
alias(libs.plugins.kotlinAndroid) | ||
alias(libs.plugins.compose.compiler) | ||
id("org.jetbrains.compose") | ||
alias(libs.plugins.kotlin.atomicfu) | ||
} | ||
|
||
android { | ||
namespace = "com.powersync.demo.backgroundsync" | ||
compileSdk = 35 | ||
|
||
defaultConfig { | ||
applicationId = "com.powersync.demo.backgroundsync" | ||
minSdk = 28 | ||
targetSdk = 35 | ||
versionCode = 1 | ||
versionName = "1.0" | ||
|
||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" | ||
} | ||
|
||
buildTypes { | ||
release { | ||
isMinifyEnabled = false | ||
proguardFiles( | ||
getDefaultProguardFile("proguard-android-optimize.txt"), | ||
"proguard-rules.pro" | ||
) | ||
} | ||
} | ||
compileOptions { | ||
sourceCompatibility = JavaVersion.VERSION_11 | ||
targetCompatibility = JavaVersion.VERSION_11 | ||
} | ||
kotlinOptions { | ||
jvmTarget = "11" | ||
} | ||
buildFeatures { | ||
compose = true | ||
} | ||
} | ||
|
||
dependencies { | ||
// When copying this example, replace "latest.release" with the current version available | ||
// at: https://central.sonatype.com/artifact/com.powersync/connector-supabase | ||
implementation("com.powersync:connector-supabase:latest.release") | ||
|
||
implementation(projects.shared) | ||
|
||
implementation(compose.material) | ||
implementation(libs.androidx.core) | ||
implementation(libs.androidx.activity.compose) | ||
implementation(libs.androidx.lifecycle.service) | ||
implementation(libs.compose.lifecycle) | ||
implementation(libs.compose.ui.tooling.preview) | ||
implementation(libs.koin.android) | ||
implementation(libs.koin.compose.viewmodel) | ||
} |
21 changes: 21 additions & 0 deletions
21
demos/supabase-todolist/androidBackgroundSync/proguard-rules.pro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
# Add project specific ProGuard rules here. | ||
# You can control the set of applied configuration files using the | ||
# proguardFiles setting in build.gradle. | ||
# | ||
# For more details, see | ||
# http://developer.android.com/guide/developing/tools/proguard.html | ||
|
||
# If your project uses WebView with JS, uncomment the following | ||
# and specify the fully qualified class name to the JavaScript interface | ||
# class: | ||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview { | ||
# public *; | ||
#} | ||
|
||
# Uncomment this to preserve the line number information for | ||
# debugging stack traces. | ||
#-keepattributes SourceFile,LineNumberTable | ||
|
||
# If you keep the line number information, uncomment this to | ||
# hide the original source file name. | ||
#-renamesourcefileattribute SourceFile |
32 changes: 32 additions & 0 deletions
32
demos/supabase-todolist/androidBackgroundSync/src/main/AndroidManifest.xml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
<?xml version="1.0" encoding="utf-8"?> | ||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> | ||
|
||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/> | ||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"/> | ||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> | ||
<uses-permission android:name="android.permission.INTERNET" /> | ||
|
||
<application | ||
android:allowBackup="true" | ||
android:icon="@mipmap/ic_launcher" | ||
android:label="@string/app_name" | ||
android:roundIcon="@mipmap/ic_launcher_round" | ||
android:supportsRtl="true" | ||
android:networkSecurityConfig="@xml/network_security_config" | ||
android:name=".MainApplication" | ||
android:theme="@style/Theme.Supabasetodolist"> | ||
<activity | ||
android:name=".MainActivity" | ||
android:exported="true" | ||
android:label="@string/app_name" | ||
android:theme="@style/Theme.Supabasetodolist"> | ||
<intent-filter> | ||
<action android:name="android.intent.action.MAIN" /> | ||
|
||
<category android:name="android.intent.category.LAUNCHER" /> | ||
</intent-filter> | ||
</activity> | ||
|
||
<service android:name=".SyncService" android:exported="false" android:foregroundServiceType="dataSync" /> | ||
</application> | ||
</manifest> |
58 changes: 58 additions & 0 deletions
58
...ist/androidBackgroundSync/src/main/java/com/powersync/demo/backgroundsync/MainActivity.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
package com.powersync.demo.backgroundsync | ||
|
||
import android.content.Intent | ||
import android.os.Bundle | ||
import androidx.activity.ComponentActivity | ||
import androidx.activity.compose.setContent | ||
import androidx.activity.enableEdgeToEdge | ||
import androidx.compose.foundation.layout.WindowInsets | ||
import androidx.compose.foundation.layout.fillMaxSize | ||
import androidx.compose.foundation.layout.systemBars | ||
import androidx.compose.foundation.layout.windowInsetsPadding | ||
import androidx.compose.material.MaterialTheme | ||
import androidx.compose.material.Surface | ||
import androidx.compose.ui.Modifier | ||
import androidx.lifecycle.lifecycleScope | ||
import com.powersync.connector.supabase.SupabaseConnector | ||
import com.powersync.demos.AppContent | ||
import io.github.jan.supabase.auth.status.SessionStatus | ||
import kotlinx.coroutines.launch | ||
import org.koin.android.ext.android.inject | ||
import org.koin.compose.KoinContext | ||
|
||
class MainActivity : ComponentActivity() { | ||
|
||
private val connector: SupabaseConnector by inject() | ||
|
||
override fun onCreate(savedInstanceState: Bundle?) { | ||
super.onCreate(savedInstanceState) | ||
enableEdgeToEdge() | ||
|
||
lifecycleScope.launch { | ||
// Watch the authentication state and start a sync foreground service once the user logs | ||
// in. | ||
connector.sessionStatus.collect { | ||
if (it is SessionStatus.Authenticated) { | ||
startForegroundService(Intent().apply { | ||
setClass(this@MainActivity, SyncService::class.java) | ||
}) | ||
} | ||
} | ||
} | ||
|
||
setContent { | ||
// We've already started Koin from our application class to be able to use the database | ||
// outside of the UI here. So, use KoinContext and AppContent instead of the App() | ||
// composable that would set up its own context. | ||
KoinContext { | ||
MaterialTheme { | ||
Surface(color = MaterialTheme.colors.background) { | ||
AppContent( | ||
modifier=Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.systemBars) | ||
) | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} |
27 changes: 27 additions & 0 deletions
27
.../androidBackgroundSync/src/main/java/com/powersync/demo/backgroundsync/MainApplication.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package com.powersync.demo.backgroundsync | ||
|
||
import android.app.Application | ||
import com.powersync.DatabaseDriverFactory | ||
import com.powersync.demos.AuthOptions | ||
import com.powersync.demos.sharedAppModule | ||
import org.koin.android.ext.koin.androidContext | ||
import org.koin.android.ext.koin.androidLogger | ||
import org.koin.core.context.startKoin | ||
import org.koin.core.module.dsl.singleOf | ||
import org.koin.dsl.module | ||
|
||
class MainApplication : Application() { | ||
override fun onCreate() { | ||
super.onCreate() | ||
|
||
startKoin { | ||
androidLogger() | ||
androidContext(this@MainApplication) | ||
|
||
modules(sharedAppModule, module { | ||
single { AuthOptions(connectFromViewModel = false) } | ||
singleOf(::DatabaseDriverFactory) | ||
}) | ||
} | ||
} | ||
} |
123 changes: 123 additions & 0 deletions
123
...list/androidBackgroundSync/src/main/java/com/powersync/demo/backgroundsync/SyncService.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
package com.powersync.demo.backgroundsync | ||
|
||
import android.app.Notification | ||
import android.content.Intent | ||
import android.content.pm.ServiceInfo | ||
import android.os.Build | ||
import androidx.core.app.NotificationChannelCompat | ||
import androidx.core.app.NotificationManagerCompat | ||
import androidx.core.app.ServiceCompat | ||
import androidx.lifecycle.LifecycleService | ||
import androidx.lifecycle.lifecycleScope | ||
import co.touchlab.kermit.Logger | ||
import com.powersync.PowerSyncDatabase | ||
import com.powersync.connector.supabase.SupabaseConnector | ||
import com.powersync.sync.SyncStatusData | ||
import io.github.jan.supabase.auth.status.SessionStatus | ||
import kotlinx.atomicfu.atomic | ||
import kotlinx.coroutines.CancellationException | ||
import kotlinx.coroutines.launch | ||
import org.koin.android.ext.android.inject | ||
|
||
class SyncService: LifecycleService() { | ||
|
||
private val connector: SupabaseConnector by inject() | ||
private val database: PowerSyncDatabase by inject() | ||
private var holdsServiceLock = false | ||
|
||
private val notificationManager get()= NotificationManagerCompat.from(this) | ||
|
||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { | ||
super.onStartCommand(intent, flags, startId) | ||
|
||
holdsServiceLock = SERVICE_RUNNING.compareAndSet(false, true) | ||
if (!holdsServiceLock) { | ||
stopSelf() | ||
return START_NOT_STICKY | ||
} | ||
|
||
createNotificationChannel() | ||
ServiceCompat.startForeground( | ||
this, | ||
startId, | ||
buildNotification(), | ||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { | ||
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC | ||
} else { | ||
0 | ||
} | ||
) | ||
|
||
lifecycleScope.launch { | ||
database.currentStatus.asFlow().collect { | ||
try { | ||
Logger.i("Sync service received status $it") | ||
notificationManager.notify(startId, buildNotification(it)) | ||
} catch (e: SecurityException) { | ||
Logger.d("Ignoring security exception when updating notification", e) | ||
} | ||
} | ||
} | ||
|
||
lifecycleScope.launch { | ||
connector.sessionStatus.collect { | ||
when (it) { | ||
is SessionStatus.Authenticated -> { | ||
database.connect(connector) | ||
} | ||
is SessionStatus.NotAuthenticated -> { | ||
database.disconnectAndClear() | ||
Logger.i("Stopping sync service, user logged out") | ||
return@collect | ||
} | ||
else -> { | ||
// Ignore | ||
} | ||
} | ||
} | ||
}.invokeOnCompletion { | ||
if (it !is CancellationException) { | ||
this.lifecycle.currentState | ||
stopSelf(startId) | ||
} | ||
} | ||
|
||
return START_NOT_STICKY | ||
} | ||
|
||
override fun onTimeout(startId: Int, fgsType: Int) { | ||
// Background sync was running for too long without the app ever being open... | ||
stopSelf(startId) | ||
} | ||
|
||
override fun onDestroy() { | ||
if (holdsServiceLock) { | ||
SERVICE_RUNNING.value = false | ||
} | ||
|
||
super.onDestroy() | ||
} | ||
|
||
private fun createNotificationChannel() { | ||
val channel = NotificationChannelCompat.Builder(CHANNEL_ID, NotificationManagerCompat.IMPORTANCE_LOW) | ||
.setName(getString(R.string.background_channel_name)) | ||
.build() | ||
notificationManager.createNotificationChannel(channel) | ||
} | ||
|
||
private fun buildNotification(state: SyncStatusData? = null): Notification = Notification.Builder(this, CHANNEL_ID).apply { | ||
setContentTitle(getString(R.string.sync_notification_title)) | ||
setSmallIcon(R.drawable.ic_launcher_foreground) | ||
|
||
if (state != null) { | ||
if (state.uploading || state.downloading) { | ||
setProgress(0, 0, true) | ||
} | ||
} | ||
}.build() | ||
|
||
private companion object { | ||
val CHANNEL_ID = "background_sync" | ||
val SERVICE_RUNNING = atomic(false) | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.