diff --git a/app/src/main/java/io/legado/app/base/BaseService.kt b/app/src/main/java/io/legado/app/base/BaseService.kt index 1ed5077c3..54b409f39 100644 --- a/app/src/main/java/io/legado/app/base/BaseService.kt +++ b/app/src/main/java/io/legado/app/base/BaseService.kt @@ -4,6 +4,7 @@ import android.app.Service import android.content.Intent import android.os.IBinder import androidx.annotation.CallSuper +import io.legado.app.help.LifecycleHelp import io.legado.app.help.coroutine.Coroutine import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -22,6 +23,7 @@ abstract class BaseService : Service(), CoroutineScope by MainScope() { @CallSuper override fun onCreate() { super.onCreate() + LifecycleHelp.onServiceCreate(this) } @CallSuper @@ -38,5 +40,6 @@ abstract class BaseService : Service(), CoroutineScope by MainScope() { override fun onDestroy() { super.onDestroy() cancel() + LifecycleHelp.onServiceDestroy(this) } } \ No newline at end of file diff --git a/app/src/main/java/io/legado/app/help/LifecycleHelp.kt b/app/src/main/java/io/legado/app/help/LifecycleHelp.kt index bf03bd87c..eea810e55 100644 --- a/app/src/main/java/io/legado/app/help/LifecycleHelp.kt +++ b/app/src/main/java/io/legado/app/help/LifecycleHelp.kt @@ -3,6 +3,7 @@ package io.legado.app.help import android.app.Activity import android.app.Application import android.os.Bundle +import io.legado.app.base.BaseService import io.legado.app.utils.LanguageUtils import java.lang.ref.WeakReference import java.util.* @@ -14,6 +15,7 @@ import java.util.* object LifecycleHelp : Application.ActivityLifecycleCallbacks { private val activities: MutableList> = arrayListOf() + private val services: MutableList> = arrayListOf() fun activitySize(): Int { return activities.size @@ -61,7 +63,7 @@ object LifecycleHelp : Application.ActivityLifecycleCallbacks { override fun onActivityDestroyed(activity: Activity) { for (temp in activities) { - if (temp.get() === activity) { + if (temp.get() != null && temp.get() === activity) { activities.remove(temp) break } @@ -76,8 +78,23 @@ object LifecycleHelp : Application.ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { activities.add(WeakReference(activity)) - if (!LanguageUtils.isSameWithSetting(activity)){ + if (!LanguageUtils.isSameWithSetting(activity)) { LanguageUtils.setConfiguration(activity) } } + + @Synchronized + fun onServiceCreate(service: BaseService) { + services.add(WeakReference(service)) + } + + @Synchronized + fun onServiceDestroy(service: BaseService) { + for (temp in services) { + if (temp.get() != null && temp.get() === service) { + services.remove(temp) + break + } + } + } } \ No newline at end of file