我正在使用ListenableWorker在workmanager中运行后台任务,我想向用户显示有关正在完成的工作的前台通知。但是worker的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?, observableType: String?, 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" />
我想你在做下面的文章或类似的事情:使用workmanager进行即时后台执行
您已经注释掉了设置通知的代码。在createNotification()
中取消注释以下内容
if (VERSION.SDK_INT >= VERSION_CODES.O) {
createNotificationChannel(channelId, name).also {
builder.setChannelId(it.id)
}
}
createNotificationChannel函数如下所示
// Create the required notification channel for O+ devices.
@TargetApi(VERSION_CODES.O)
private fun createNotificationChannel(
channelId: String,
name: String
): NotificationChannel {
return NotificationChannel(
channelId, name, NotificationManager.IMPORTANCE_LOW
).also { channel ->
notificationManager.createNotificationChannel(channel)
}
}