You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
2.2 KiB
70 lines
2.2 KiB
package com.gyf.lib.service
|
|
|
|
import android.content.Context
|
|
import androidx.work.Data
|
|
import androidx.work.Worker
|
|
import androidx.work.WorkerParameters
|
|
import com.google.gson.Gson
|
|
import com.google.gson.reflect.TypeToken
|
|
import com.gyf.lib.util.*
|
|
import com.orhanobut.logger.Logger
|
|
import java.net.SocketTimeoutException
|
|
|
|
data class NotificationVo(val title: String, val content: String, val id: Int)
|
|
|
|
data class PageDto(val currentPage: Long, val pageSize: Int = 10)
|
|
|
|
data class NotificationDto(
|
|
val receiverId: Int,
|
|
val receiverClient: String,
|
|
override val token: Token,
|
|
val page: PageDto? = null
|
|
) : BaseToken()
|
|
|
|
/**
|
|
* 通知接收客户端
|
|
*
|
|
*/
|
|
enum class ReceiverType {
|
|
//前台
|
|
Foreground,
|
|
|
|
//后台
|
|
Background
|
|
}
|
|
|
|
class NotificationWorker(context: Context, workerParams: WorkerParameters) :
|
|
Worker(context, workerParams) {
|
|
|
|
override fun doWork(): Result {
|
|
TokenManager.token?.let {
|
|
return try {
|
|
Logger.i("开始拉取通知")
|
|
val data = HttpClient.postAsync<NotificationVo>(
|
|
url = Api.buildUrl(NotificationApi.Pull),
|
|
jsonParam = NotificationDto(
|
|
receiverId = it.id,
|
|
receiverClient = inputData.getString("receiverClient")
|
|
?: throw IllegalArgumentException("缺少receiverClient参数"),
|
|
token = it
|
|
),
|
|
type = object : TypeToken<ApiResponse<NotificationVo>>() {}.type
|
|
)
|
|
val result =
|
|
Data.Builder().putString(NotificationVo::class.java.name, Gson().toJson(data))
|
|
.build()
|
|
Logger.i("拉取通知成功:\n${result}")
|
|
Result.success(result)
|
|
} catch (e: SocketTimeoutException) {
|
|
Logger.e(e, "网络异常,拉取通知失败稍后再试")
|
|
Result.retry()
|
|
} catch (e: Exception) {
|
|
Logger.e(e, "发生未知异常,中止任务")
|
|
Result.failure()
|
|
}
|
|
}
|
|
Logger.w("找不到token信息,中止任务")
|
|
return Result.failure()
|
|
}
|
|
|
|
} |