Я создал сервис для того, чтоб когда приложение закрывалось, он выполнил кое-какой код напоследок. Вставил участок кода в onTaskCanceled, который полностью работает в onBackPressed при нажатии кнопки назад, но не работает ПОЛНОСТЬЮ в этом методе, а если точнее, то частично работает, отправляется только один запрос Firebase. Отмечу в коде, какой запрос действует. Запрос, связанный с Firestore, не работает вообще. Когда я смотрел через режим отладки, то само приложение просто пробегало данный код, но при этом ни в одном блоке кода, который возникает тогда, когда запрос удачный или неудачный, код не выполнялся. Бывали такие случаи, когда весь код выполнялся правильно, но они редки и случайны. Сервис спустя около 5ти секунд вызывает онДестрой, даже если нет команд stopService и stopSelf в onTaskRemoved.
class ClosingService : Service() {
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return START_STICKY
}
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
val sharedPreferences = getSharedPreferences("sharedPreferences", MODE_PRIVATE)
val currentRoomID: String = sharedPreferences.getString(CURRENT_ROOM, "") ?: ""
val myRef: DatabaseReference = Firebase.database.getReference(ROOMS).child(currentRoomID)
// этот запрос работает, остальные нет
sharedPreferences.getString(MainActivity.LOGIN, "")?.let { myRef.child(MainActivity.PLAYERS).child(it).removeValue() }
val playerIsHost = sharedPreferences.getBoolean(IS_HOST, false)
Log.d(TAG, "onTaskRemoved: ")
if (playerIsHost) {
Log.d(TAG, "onTaskRemoved: ")
Firebase.firestore.collection(ROOMS).document(currentRoomID)
.delete()
.addOnSuccessListener {
Log.d(TAG, "onTaskRemoved: ")
myRef.removeValue().addOnSuccessListener {
Log.d(TAG, "onTaskRemoved: ")
stopSelf() }
}.addOnCanceledListener {
Log.d(TAG, "Ошибка")
}
}
}
}
Код, откуда стартуется сервис
import android.content.Intent
import android.content.SharedPreferences
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.github.terrakok.cicerone.Router
import com.github.terrakok.cicerone.androidx.AppNavigator
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.itmc.musiccenter.cicerone_navigation.MyRouter
import com.itmc.musiccenter.cicerone_navigation.Screens
import java.util.*
class MainActivity : AppCompatActivity() {
companion object {
internal lateinit var router: Router
internal lateinit var sharedPreferences: SharedPreferences
internal lateinit var editor: SharedPreferences.Editor
internal lateinit var res: Resources
internal const val IS_HOST = "isHost"
internal const val CURRENT_ROOM = "currentRoom"
internal const val TOKEN = "myToken"
internal const val LOGIN = "login"
internal const val USER_UID = "userUID"
internal const val USERS = "users"
internal const val TAG = "myTag"
internal const val PLAYERS = "Players"
internal const val ROOMS = "Rooms"
internal const val CHAT = "chat"
internal const val STATUS = "status"
internal const val WORD = "word"
internal const val PLAYER_WRITING_WORD = "playerWritingWord"
internal const val PLAYER_CHOOSING_SONG = "playerChoosingSong"
internal const val SELECTED_MUSIC = "selectedMusic"
internal const val MUSICS_IN_THIS_ROUND = "musicsInThisRound"
internal const val CURRENT_TRACK_RATING = "CurrentTrackRating"
internal const val VOTED_FOR_SKIP_MUSIC = "VotedForSkipMusic"
internal const val CURRENT_STATUS = "currentStatus"
internal const val USER_VOTED_FOR_SKIP = "UserVotedForSkip"
internal const val CURRENT_ROOM_ROUNDS = "currentRoomRounds"
internal const val COUNT_OF_RATE_PLAYERS = "countOfRatePlayers"
internal const val THROWING_LOTS = "throwingLots"
internal const val WRITE_WORD = "writeWord"
internal const val CHOOSE_SONG = "chooseSong"
internal const val PLAYING_MUSIC = "playingMusic"
internal const val RATE_THE_MUSIC = "rateTheMusic"
internal const val END_GAME = "endGame"
internal const val WRITE_WORD_END = "writeWordEnd"
internal const val CHOOSE_SONG_END = "chooseSongEnd"
internal const val PLAYING_MUSIC_END = "playingMusicEnd"
internal const val RATE_THE_MUSIC_END = "rateTheMusicEnd"
internal const val RESTART = "restart"
internal const val BACKGROUND_PLAY_SETTING = "backgroundPlaySetting"
internal const val LOCALISATION = "localisation"
internal const val CURRENT_POINTS = "currentPoints"
}
private val myRouter = MyRouter()
private val navigator = AppNavigator(this, R.id.container)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(TAG, "onCreate: app started")
sharedPreferences = getSharedPreferences("sharedPreferences", MODE_PRIVATE)
editor = sharedPreferences.edit()
val i = Intent(this, ClosingService::class.java)
startService(i)
val locale = sharedPreferences.getString(LOCALISATION, "ru")?.let { Locale(it) }
if (locale != null) {
Locale.setDefault(locale)
}
val configuration = Configuration()
configuration.locale = locale
baseContext?.resources?.updateConfiguration(configuration, null)
val currentUser = Firebase.auth.currentUser
router = if(currentUser != null){
Firebase.auth.currentUser!!.reload()
myRouter.router.also { it.newRootScreen(Screens.mainMenuFragment()) }
} else {
myRouter.router.also { it.newRootScreen(Screens.signInFragment()) }
}
res = resources
}
override fun onResume() {
super.onResume()
myRouter.navigatorHolder.setNavigator(navigator)
}
override fun onPause() {
super.onPause()
myRouter.navigatorHolder.removeNavigator()
}
}
манифест
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.itmc.musiccenter">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".App"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MusicCenter"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ClosingService"
android:stopWithTask="false" />
</application>
</manifest>