Skip to content

Instantly share code, notes, and snippets.

@dave08
Created October 18, 2017 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dave08/85e649082c2004aea879c117f8c3ae6b to your computer and use it in GitHub Desktop.
Save dave08/85e649082c2004aea879c117f8c3ae6b to your computer and use it in GitHub Desktop.
Starting sync with coroutines
override fun onSyncStart(context: Context, currSyncResult: SyncResult) {
runBlocking {
syncLock.lock()
try {
syncApi.getResponse(context)
.doOnNext { info { "Received response, dispatching api requests ..." } }
.awaitSingle().apply {
syncParser.dispatchRequests(apiParser(this))
}
chainManager.updateHostResolves()
info { "Sync sucessfully completed." }
context.sendBroadcast(Intent(ServerProvider.ACTION_SYNC).apply {
putExtra(ServerProvider.SYNC_STATE, SyncStatus.COMPLETE_WITH_NO_ERRORS)
})
} catch (e: Throwable) {
error { "Error in getting sync response: $e" }
context.sendBroadcast(Intent(ServerProvider.ACTION_SYNC).apply {
putExtra(ServerProvider.SYNC_STATE, SyncStatus.COMPLETE_WITH_GENERAL_ERRORS)
})
} finally {
syncLock.unlock()
}
}
}
class ApplicationService(): IntentService("ApplicationService"), AnkoLogger {
private val eventBus: EventBus by injectValue()
override fun onCreate() {
setIntentRedelivery(true)
super.onCreate()
info { "Application Service created" }
}
override fun onDestroy() {
super.onDestroy()
info { "Application Service destroyed" }
}
override fun onHandleIntent(intent: Intent) {
val bundle = intent.extras
val intentParams = bundle?.keySet()?.joinToString(";", "(", ")") { key ->
"$key:${bundle.get(key)}"
} ?: ""
Log.i("ApplicationService", "Started with ${intent.action} $intentParams")
when (intent.action) {
Intent.ACTION_BOOT_COMPLETED -> eventBus.post(OnBoot())
ConnectivityManager.CONNECTIVITY_ACTION -> {
if (isConnected) {
eventBus.post(OnConnectivity())
}
else {
eventBus.post(OnConnectivityLost())
}
}
Intent.ACTION_PACKAGE_CHANGED -> eventBus.post(OnPackageChanged(intent.data.encodedSchemeSpecificPart))
else -> eventBus.post(OnIntent(this, intent))
}
}
private val isConnected: Boolean
get() = connectivityManager.activeNetworkInfo?.isConnected ?: false
}
interface SyncHandler {
fun onSyncStart(context: Context, currSyncResult: SyncResult)
fun onSyncError(syncResult: SyncResult, exception: Exception)
}
class DeviceStateSyncAdapter(context: Context, autoInitialize: Boolean) : AbstractThreadedSyncAdapter(context, autoInitialize) {
private val syncHandler by injectValue<SyncHandler>()
private val mAccountManager: AccountManager
init {
mAccountManager = AccountManager.get(context)
}
override fun onPerformSync(account: Account, bundle: Bundle, s: String, contentProviderClient: ContentProviderClient, syncResult: SyncResult) {
try {
syncHandler.onSyncStart(context, syncResult)
} catch (e: Exception) {
syncHandler.onSyncError(syncResult, e)
}
}
companion object {
private val TAG = "DeviceStateSync"
}
}
class DeviceStateSyncService : Service(), AnkoLogger {
/*
* Instantiate the sync adapter object.
*/
override fun onCreate() {
/*
* Create the sync adapter as a singleton.
* Set the sync adapter as syncable
* Disallow parallel syncs
*/
synchronized (sSyncAdapterLock) {
if (sSyncAdapter == null) {
sSyncAdapter = DeviceStateSyncAdapter(applicationContext, true)
}
}
info { "DeviceStateSyncService created." }
}
override fun onDestroy() {
super.onDestroy()
info { "DeviceStateSyncService destroyed." }
}
/**
* Return an object that allows the system to invoke
* the sync adapter.
*/
override fun onBind(intent: Intent): IBinder? {
info { "DeviceStateSyncService bind..." }
/*
* Get the object that allows external processes
* to call onPerformSync(). The object is created
* in the base class code when the SyncAdapter
* constructors call super()
*/
return sSyncAdapter!!.syncAdapterBinder
}
override fun onUnbind(intent: Intent?): Boolean {
info { "DeviceStateSyncService unbind." }
return super.onUnbind(intent)
}
override fun onRebind(intent: Intent?) {
super.onRebind(intent)
info { "DeviceStateSyncService rebind..." }
}
companion object {
// Storage for an instance of the sync adapter
private var sSyncAdapter: DeviceStateSyncAdapter? = null
// Object to use as a thread-safe lock
private val sSyncAdapterLock = Object()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment