11package org.ole.planet.myplanet.datamanager
22
3+ import android.app.NotificationChannel
34import android.app.NotificationManager
45import android.app.Service
56import android.content.Context
67import android.content.Intent
78import android.content.SharedPreferences
89import android.os.IBinder
910import androidx.core.app.NotificationCompat
11+ import androidx.core.content.ContextCompat
1012import androidx.localbroadcastmanager.content.LocalBroadcastManager
1113import io.realm.Realm
1214import kotlinx.coroutines.CoroutineScope
1315import kotlinx.coroutines.Dispatchers
1416import kotlinx.coroutines.launch
1517import okhttp3.ResponseBody
1618import org.ole.planet.myplanet.MainApplication.Companion.createLog
19+ import org.ole.planet.myplanet.R
1720import org.ole.planet.myplanet.model.Download
1821import org.ole.planet.myplanet.model.RealmMyLibrary
1922import org.ole.planet.myplanet.utilities.FileUtils.availableExternalMemorySize
@@ -48,6 +51,8 @@ class MyDownloadService : Service() {
4851 preferences = getSharedPreferences(PREFS_NAME , MODE_PRIVATE )
4952 notificationManager = getSystemService(NOTIFICATION_SERVICE ) as NotificationManager
5053
54+ startForegroundServiceWithNotification()
55+
5156 val urlsKey = intent?.getStringExtra(" urls_key" ) ? : " url_list_key"
5257 val urlSet = preferences.getStringSet(urlsKey, emptySet()) ? : emptySet()
5358
@@ -69,6 +74,20 @@ class MyDownloadService : Service() {
6974 return START_STICKY
7075 }
7176
77+ private fun startForegroundServiceWithNotification () {
78+ val channelId = " DownloadChannel"
79+ val channel = NotificationChannel (channelId, " Download Service" , NotificationManager .IMPORTANCE_LOW )
80+ notificationManager?.createNotificationChannel(channel)
81+
82+ notificationBuilder = NotificationCompat .Builder (this , channelId)
83+ .setContentTitle(getString(R .string.downloading_files))
84+ .setContentText(getString(R .string.preparing_download))
85+ .setSmallIcon(R .drawable.ic_download)
86+ .setProgress(100 , 0 , true )
87+
88+ startForeground(1 , notificationBuilder!! .build())
89+ }
90+
7291 private fun initDownload (url : String , fromSync : Boolean ) {
7392 val retrofitInterface = ApiClient .client?.create(ApiInterface ::class .java)
7493 try {
@@ -256,7 +275,7 @@ class MyDownloadService : Service() {
256275 putExtra(" urls_key" , urlsKey)
257276 putExtra(" fromSync" , fromSync)
258277 }
259- context.startService( intent)
278+ ContextCompat .startForegroundService(context, intent)
260279 }
261280 }
262281}
0 commit comments