如何解决SetForegroundAsync 在 Workmanager 的 ListenableWorker 中创建前台服务不起作用
我正在使用 ListenableWorker 在 workmanager 中运行后台任务,我想向用户显示有关正在完成工作的前台通知。但是工作人员的 OnStart 函数下的 SetForegroundAsync 函数没有生成通知。这是代码 -
class PostUploadWorker(context: Context,params: WorkerParameters): ListenableWorker(context,params) {
companion object{
fun getBuilder(postDtoJson: String,postEntityId: String? = null,type: String? = null,mediaId: String? = null
): OneTimeWorkRequest.Builder {
val data = workDataOf(
POST to postDtoJson,POST_ENTITY_ID to postEntityId,MEDIA_TYPE to type,MEDIA_ID to mediaId
)
return OneTimeWorkRequest.Builder(PostUploadWorker::class.java).setInputData(data)
}
}
private fun getPostMediaType(mediaTye: String?): String {
if (mediaTye == TYPE_VIDEO) {
return PostMediaType.VIDEO.stringName
}
return PostMediaType.AUDIO.stringName
}
private fun createForegroundInfo(): ForegroundInfo {
// Use a different id for each Notification.
val notificationId = 1
val notificationn = createNotification()
Timber.e("asdf: /api/v1/feed inside CreateForegroundInfo ${notificationn}")
return ForegroundInfo(notificationId,notificationn)
}
private fun createNotification(): Notification {
// This PendingIntent can be used to cancel the Worker.
val intent = WorkManager.getInstance(AppController.getInstance()).createCancelPendingIntent(id)
val builder = NotificationCompat.Builder( applicationContext,"123")
.setContentTitle("uploading post")
.setTicker("title")
.setOngoing(true)
.setChannelId("123")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.addAction(R.drawable.notification_bg,"cancel",intent)
/* if (VERSION.SDK_INT >= VERSION_CODES.O) {
createNotificationChannel(channelId,name).also {
builder.setChannelId(it.id)
}
} */
return builder.build()
}
override fun startWork(): ListenableFuture<Result> {
Timber.e("post upload worker")
setForegroundAsync(createForegroundInfo())
val future: SettableFuture<Result> = SettableFuture.create()
val mediaId = inputData.getString(MEDIA_ID)
val type = inputData.getString(MEDIA_TYPE)
val post = inputData.getString(POST)
val postEntityId = inputData.getString(POST_ENTITY_ID)!!
return try {
val postDto = Gson().fromJson(post,SubmitPostDto::class.java)
val uploadPostDto = postDto.toUploadPost()
if (type == TYPE_VIDEO) {
uploadPostDto.videoId = mediaId
} else {
uploadPostDto.audioId = mediaId
}
var extraInfo = ExtraInfoDto()
PostCreationRepository.getSinglePost(postEntityId)
.subscribeOn(Schedulers.io())
.doOnSuccess {
extraInfo = Gson().fromJson(it?.extraInfo,ExtraInfoDto::class.java)
}.subscribe()
PostCreationRepository.uploadPost(uploadPostDto,object : ObservableCallBack {
override fun observableSuccess(`object`: Any?,observableType: String?,observableId: String?) {
Timber.e("asdf: /api/v1/feed upload worker success $uploadPostDto")
val idModel = `object` as IdModel
Timber.e("asdf: /api/v1/feed upload worker success2 ${idModel.id}")
PostCreationRepository.setPostUploaded(postDto.postId,idModel.id)
val data = workDataOf(
POST_SERVER_ID to idModel.id,POST_ENTITY_ID to postEntityId
)
future.set(Result.success(data))
logEvent(extraInfo,Value.Success,getPostMediaType(type),idModel.id)
}
override fun observableFailure(`object`: Any?,observableId: String?) {
Timber.e("asdf: /api/v1/feed upload worker failure $`object`")
PostCreationRepository.setPostFailStatus(postDto.postId)
future.set(Result.failure())
logEvent(extraInfo,Value.Failed,getPostMediaType(type))
}
})
future
} catch (e: Exception) {
Timber.e("upload worker $e")
PostCreationRepository.setPostFailStatus(postEntityId)
future.set(Result.failure())
future
}
}
private fun logEvent(extraInfo: ExtraInfoDto,status: String,type: String,postId: String? = null) {
Bundle().apply {
putString(Attr.PostId,postId)
putString(Attr.Status,status)
putString(Attr.Source,extraInfo.postSource)
putString(Attr.Type,extraInfo.postType)
putString(Attr.MediaType,type)
}.also {
EventTracker.trackEvent(Event.PostPublishAPIStatus,it)
}
}
}
这是 ManiFest 文件所需的代码--
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<service
android:name="androidx.work.impl.foreground.SystemForegroundService"
android:foregroundServiceType="location|dataSync"
tools:node="merge"
tools:ignore="Instantiatable" />
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。