okhttp-sse in background



我正在构建一个移动应用程序,这意味着在后台服务中获得服务器发送的事件。当应用程序打开时,我可以获得SSE事件,但当应用程序关闭时,我不再接收SSE事件,即使它们在后台服务中被接受。有解决方案吗?

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<service
android:name=".NotificationService"
android:enabled="true"
android:exported="true"
android:process=":MyApp_Notifications"/>

MainActivity.kt

startService(Intent(applicationContext, NotificationService::class.java))

NotificationService.kt

class NotificationService : Service() {
var notifChannelId = "RD_N_D_C"
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
createNotificationChannel()
val eventSourceListener = object : EventSourceListener() {
override fun onEvent(
eventSource: EventSource,
id: String?,
type: String?,
data: String
) {
super.onEvent(eventSource, id, type, data)
Log.e(TAG, "nNOTIFn")
val data = JSONTokener(data).nextValue() as JSONObject
var builder = NotificationCompat.Builder(this@NotificationService, notifChannelId)
.setSmallIcon(R.drawable.notification_no_bg)
.setContentTitle(data.optString("title"))
.setContentText(data.optString("text"))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
with(NotificationManagerCompat.from(this@NotificationService)) {
notify(Random.nextInt(100000, 999999), builder.build())
}
}
override fun onClosed(eventSource: EventSource) {
Log.e(TAG, "nError - Closedn")
super.onClosed(eventSource)
}
override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
Log.e(TAG, "nError - Failuren")
super.onFailure(eventSource, t, response)
}
}
val client = OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.MINUTES)
.writeTimeout(10, TimeUnit.MINUTES)
.build()
val request = Request.Builder()
.url("https://random.website.that/sends/sse/events")
.header("Accept", "application/json; q=0.5")
.addHeader("Accept", "text/event-stream")
.build()
EventSources.createFactory(client)
.newEventSource(request = request, listener = eventSourceListener)
client.newCall(request).enqueue(responseCallback = object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.e(TAG, "nError - API Failuren")
}
override fun onResponse(call: Call, response: Response) {}
})
return START_STICKY
}
// The rest is just onBind(), createNotificationChannel() & onTaskRemoved()

我不知道你不能从后台服务发送通知。要解决这个问题,你所要做的就是把它改成前台服务。

改变
startService(Intent(applicationContext, NotificationService::class.java))

val notifIntent = Intent(applicationContext, NotificationService::class.java)
applicationContext.startForegroundService(notifIntent)

你还需要在你的AndroidManifest.xml文件中添加前台服务权限。

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

最新更新