android okhttp-sse在后台

6rqinv9w  于 2023-01-24  发布在  Android
关注(0)|答案(1)|浏览(975)

我正在构建一个移动的应用程序,该应用程序用于在后台服务中获取服务器发送的事件。我可以在应用程序打开时获取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, "\nNOTIF\n")
                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 - Closed\n")
                super.onClosed(eventSource)
            }

            override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
                Log.e(TAG, "\nError - Failure\n")
                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 Failure\n")
            }
            override fun onResponse(call: Call, response: Response) {}
        })

        return START_STICKY
    }
    // The rest is just onBind(), createNotificationChannel() & onTaskRemoved()
oug3syen

oug3syen1#

我没有意识到你不能从后台服务发送通知。要解决这个问题,你所要做的就是把它改为前台服务。
变更

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"/>

相关问题