Skip to content
This repository was archived by the owner on Jul 2, 2024. It is now read-only.

Commit bb42a57

Browse files
committed
Optimize DownloadService
1 parent 9ef5086 commit bb42a57

File tree

1 file changed

+49
-42
lines changed

1 file changed

+49
-42
lines changed

app/src/main/kotlin/com/sanmer/mrepo/service/DownloadService.kt

+49-42
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
package com.sanmer.mrepo.service
22

33
import android.Manifest
4+
import android.annotation.SuppressLint
45
import android.app.Notification
56
import android.content.Context
67
import android.content.Intent
7-
import android.content.pm.PackageManager
88
import android.os.Build
99
import android.os.Parcel
1010
import android.os.Parcelable
1111
import androidx.core.app.NotificationCompat
1212
import androidx.core.app.NotificationManagerCompat
1313
import androidx.core.app.ServiceCompat
14-
import androidx.core.content.ContextCompat
1514
import androidx.documentfile.provider.DocumentFile
1615
import androidx.lifecycle.LifecycleService
1716
import androidx.lifecycle.lifecycleScope
@@ -43,11 +42,11 @@ import javax.inject.Inject
4342

4443
@AndroidEntryPoint
4544
class DownloadService : LifecycleService() {
45+
@Inject lateinit var userPreferencesRepository: UserPreferencesRepository
46+
4647
private val context: Context by lazy { applicationContext }
4748
private val tasks = mutableListOf<TaskItem>()
4849

49-
@Inject lateinit var userPreferencesRepository: UserPreferencesRepository
50-
5150
init {
5251
lifecycleScope.launch {
5352
while (isActive) {
@@ -61,7 +60,7 @@ class DownloadService : LifecycleService() {
6160
.flowOn(Dispatchers.IO)
6261
.onEach { (item, progress) ->
6362
if (progress != 0f) {
64-
notifyProgress(item, progress)
63+
onProgressChanged(item, progress)
6564
}
6665
}
6766
.launchIn(lifecycleScope)
@@ -70,9 +69,17 @@ class DownloadService : LifecycleService() {
7069
override fun onCreate() {
7170
Timber.d("DownloadService onCreate")
7271
super.onCreate()
72+
7373
setForeground()
7474
}
7575

76+
override fun onDestroy() {
77+
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_DETACH)
78+
79+
Timber.d("DownloadService onDestroy")
80+
super.onDestroy()
81+
}
82+
7683
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
7784
lifecycleScope.launch {
7885
val item = intent?.taskItemOrNull ?: return@launch
@@ -85,7 +92,7 @@ class DownloadService : LifecycleService() {
8592

8693
val df = downloadPath.createFile("*/*", item.filename)
8794
if (df == null) {
88-
notifyFailure(item, "Failed to create file")
95+
onDownloadFailed(item, "Failed to create file")
8996
return@launch
9097
}
9198

@@ -94,7 +101,7 @@ class DownloadService : LifecycleService() {
94101
contentResolver.openOutputStream(df.uri)
95102
)
96103
} catch (e: FileNotFoundException) {
97-
notifyFailure(item, e.message)
104+
onDownloadFailed(item, e.message)
98105
return@launch
99106
}
100107

@@ -105,15 +112,15 @@ class DownloadService : LifecycleService() {
105112
}
106113

107114
override fun onSuccess() {
108-
notifySuccess(item)
115+
onDownloadSucceeded(item)
109116

110117
progressFlow.value = item to 0f
111118
listeners[item]?.onSuccess()
112119
tasks.remove(item)
113120
}
114121

115122
override fun onFailure(e: Throwable) {
116-
notifyFailure(item, e.message)
123+
onDownloadFailed(item, e.message)
117124

118125
progressFlow.value = item to 0f
119126
listeners[item]?.onFailure(e)
@@ -137,12 +144,6 @@ class DownloadService : LifecycleService() {
137144
return super.onStartCommand(intent, flags, startId)
138145
}
139146

140-
override fun onDestroy() {
141-
Timber.d("DownloadService onDestroy")
142-
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
143-
super.onDestroy()
144-
}
145-
146147
private fun setForeground() {
147148
val notification = NotificationCompat.Builder(this, NotificationUtils.CHANNEL_ID_DOWNLOAD)
148149
.setSmallIcon(R.drawable.launcher_outline)
@@ -156,31 +157,7 @@ class DownloadService : LifecycleService() {
156157
startForeground(NotificationUtils.NOTIFICATION_ID_DOWNLOAD, notification)
157158
}
158159

159-
private fun buildNotification(
160-
title: String?,
161-
desc: String?,
162-
silent: Boolean = false,
163-
ongoing: Boolean = false,
164-
) = NotificationCompat.Builder(context, NotificationUtils.CHANNEL_ID_DOWNLOAD)
165-
.setSmallIcon(R.drawable.launcher_outline)
166-
.setContentTitle(title)
167-
.setSubText(desc)
168-
.setSilent(silent)
169-
.setOngoing(ongoing)
170-
.setGroup(GROUP_KEY)
171-
172-
private fun notify(id: Int, notification: Notification) {
173-
val notificationId = NotificationUtils.NOTIFICATION_ID_DOWNLOAD + id
174-
NotificationManagerCompat.from(context).apply {
175-
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS)
176-
!= PackageManager.PERMISSION_GRANTED
177-
) return
178-
179-
notify(notificationId, notification)
180-
}
181-
}
182-
183-
private fun notifyProgress(item: TaskItem, progress: Float) {
160+
private fun onProgressChanged(item: TaskItem, progress: Float) {
184161
val notification = buildNotification(
185162
title = item.title,
186163
desc = item.desc,
@@ -193,7 +170,7 @@ class DownloadService : LifecycleService() {
193170
notify(item.taskId, notification.build())
194171
}
195172

196-
private fun notifySuccess(item: TaskItem) {
173+
private fun onDownloadSucceeded(item: TaskItem) {
197174
val message = context.getString(R.string.message_download_success)
198175
val notification = buildNotification(
199176
title = item.title,
@@ -206,7 +183,7 @@ class DownloadService : LifecycleService() {
206183
notify(item.taskId, notification.build())
207184
}
208185

209-
private fun notifyFailure(item: TaskItem, message: String?) {
186+
private fun onDownloadFailed(item: TaskItem, message: String?) {
210187
val msg = message ?: context.getString(R.string.unknown_error)
211188
val notification = buildNotification(
212189
title = item.title,
@@ -219,6 +196,36 @@ class DownloadService : LifecycleService() {
219196
notify(item.taskId, notification.build())
220197
}
221198

199+
private fun buildNotification(
200+
title: String?,
201+
desc: String?,
202+
silent: Boolean = false,
203+
ongoing: Boolean = false,
204+
) = NotificationCompat.Builder(context, NotificationUtils.CHANNEL_ID_DOWNLOAD)
205+
.setSmallIcon(R.drawable.launcher_outline)
206+
.setContentTitle(title)
207+
.setSubText(desc)
208+
.setSilent(silent)
209+
.setOngoing(ongoing)
210+
.setGroup(GROUP_KEY)
211+
212+
213+
@SuppressLint("MissingPermission")
214+
private fun notify(id: Int, notification: Notification) {
215+
val granted = if (BuildCompat.atLeastT) {
216+
PermissionCompat.checkPermissions(
217+
context,
218+
listOf(Manifest.permission.POST_NOTIFICATIONS)
219+
).allGranted
220+
} else {
221+
true
222+
}
223+
224+
NotificationManagerCompat.from(this).apply {
225+
if (granted) notify(id, notification)
226+
}
227+
}
228+
222229
data class TaskItem(
223230
val key: String,
224231
val url: String,

0 commit comments

Comments
 (0)