Skip to content
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

sync: smoother background thread (fixes #4638) #4639

Merged
merged 3 commits into from
Oct 15, 2024
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
4 changes: 2 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ android {
applicationId "org.ole.planet.myplanet"
minSdkVersion 26
targetSdkVersion 34
versionCode 2030
versionName "0.20.30"
versionCode 2031
versionName "0.20.31"
ndkVersion '21.3.6528147'
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
Expand Down
90 changes: 55 additions & 35 deletions app/src/main/java/org/ole/planet/myplanet/MainApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import java.net.URL
import java.util.Date
import java.util.UUID
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.runBlocking

class MainApplication : Application(), Application.ActivityLifecycleCallbacks {
companion object {
Expand Down Expand Up @@ -76,23 +77,30 @@ class MainApplication : Application(), Application.ActivityLifecycleCallbacks {
lateinit var defaultPref: SharedPreferences

fun createLog(type: String) {
service = DatabaseService(context)
val mRealm = service.realmInstance
if (!mRealm.isInTransaction) {
mRealm.beginTransaction()
}
val log = mRealm.createObject(RealmApkLog::class.java, "${UUID.randomUUID()}")
val model = UserProfileDbHandler(context).userModel
if (model != null) {
log.parentCode = model.parentCode
log.createdOn = model.planetCode
log.userId = model.id
runBlocking {
withContext(Dispatchers.IO) {
val realm = Realm.getDefaultInstance()
try {
realm.executeTransaction { r ->
val log = r.createObject(RealmApkLog::class.java, "${UUID.randomUUID()}")
val model = UserProfileDbHandler(context).userModel
if (model != null) {
log.parentCode = model.parentCode
log.createdOn = model.planetCode
log.userId = model.id
}
log.time = "${Date().time}"
log.page = ""
log.version = getVersionName(context)
log.type = type
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
realm.close()
}
}
}
log.time = "${Date().time}"
log.page = ""
log.version = getVersionName(context)
log.type = type
mRealm.commitTransaction()
}

private fun applyThemeMode(themeMode: String?) {
Expand Down Expand Up @@ -129,6 +137,7 @@ class MainApplication : Application(), Application.ActivityLifecycleCallbacks {
responseCode in 200..299

} catch (e: Exception) {
e.printStackTrace()
false
}
}
Expand Down Expand Up @@ -266,38 +275,49 @@ class MainApplication : Application(), Application.ActivityLifecycleCallbacks {
if (isFirstLaunch) {
isFirstLaunch = false
} else {
val fromForeground = "foreground"
createLog(fromForeground)
applicationScope.launch {
createLog("foreground")
}
}
}

private fun onAppBackgrounded() {}

private fun onAppStarted() {
val newStart = "new login"
createLog(newStart)
applicationScope.launch {
createLog("new login")
}
}

private fun onAppClosed() {}

private fun handleUncaughtException(e: Throwable) {
e.printStackTrace()
if (!mRealm.isInTransaction) {
mRealm.beginTransaction()
}
val log = mRealm.createObject(RealmApkLog::class.java, "${UUID.randomUUID()}")
val model = UserProfileDbHandler(this).userModel
if (model != null) {
log.parentCode = model.parentCode
log.createdOn = model.planetCode
log.userId = model.id
runBlocking {
launch(Dispatchers.IO) {
try {
val realm = Realm.getDefaultInstance()
realm.executeTransaction { r ->
val log = r.createObject(RealmApkLog::class.java, "${UUID.randomUUID()}")
val model = UserProfileDbHandler(this@MainApplication).userModel
if (model != null) {
log.parentCode = model.parentCode
log.createdOn = model.planetCode
log.userId = model.id
}
log.time = "${Date().time}"
log.page = ""
log.version = getVersionName(this@MainApplication)
log.type = RealmApkLog.ERROR_TYPE_CRASH
log.setError(e)
}
realm.close()
} catch (ex: Exception) {
ex.printStackTrace()
}
}
}
log.time = "${Date().time}"
log.page = ""
log.version = getVersionName(this)
log.type = RealmApkLog.ERROR_TYPE_CRASH
log.setError(e)
mRealm.commitTransaction()

val homeIntent = Intent(Intent.ACTION_MAIN)
homeIntent.addCategory(Intent.CATEGORY_HOME)
homeIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import io.realm.Realm
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.ResponseBody
import org.ole.planet.myplanet.model.Download
import org.ole.planet.myplanet.model.RealmMyLibrary
Expand Down Expand Up @@ -207,14 +208,16 @@ class MyDownloadService : Service() {
private fun changeOfflineStatus() {
CoroutineScope(Dispatchers.IO).launch {
val currentFileName = getFileNameFromUrl(urls[currentIndex])
mRealm.executeTransaction { realm ->
realm.where(RealmMyLibrary::class.java)
.equalTo("resourceLocalAddress", currentFileName)
.findAll()
?.forEach {
it.resourceOffline = true
it.downloadedRev = it._rev
}
withContext(Dispatchers.Main) { // Switch to the main thread
mRealm.executeTransaction { realm ->
realm.where(RealmMyLibrary::class.java)
.equalTo("resourceLocalAddress", currentFileName)
.findAll()
?.forEach {
it.resourceOffline = true
it.downloadedRev = it._rev
}
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ import androidx.recyclerview.widget.RecyclerView
import com.afollestad.materialdialogs.*
import com.google.android.material.textfield.TextInputLayout
import io.realm.*
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
import okhttp3.ResponseBody
import org.ole.planet.myplanet.BuildConfig
import org.ole.planet.myplanet.MainApplication.Companion.applicationScope
import org.ole.planet.myplanet.MainApplication.Companion.context
import org.ole.planet.myplanet.MainApplication.Companion.createLog
import org.ole.planet.myplanet.R
Expand Down Expand Up @@ -343,7 +345,9 @@ abstract class SyncActivity : ProcessUserDataActivity(), SyncListener, CheckVers
syncIconDrawable.stop()
syncIconDrawable.selectDrawable(0)
syncIcon.invalidateDrawable(syncIconDrawable)
createLog("synced successfully")
applicationScope.launch {
createLog("synced successfully")
}
showSnack(findViewById(android.R.id.content), getString(R.string.sync_completed))
downloadAdditionalResources()
if (defaultPref.getBoolean("beta_auto_download", false)) {
Expand Down