为什么我的广播接收器停止工作?

问题描述 投票:0回答:1

我使用BroadcastReceiver来接收系统通知。当收到通知时,我需要向服务器发送一些数据。 对我来说重要的是,当应用程序处于后台时接收广播和发送数据才能工作(这是其主要任务)。

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class Airplane : BroadcastReceiver() {
@SuppressLint("UnsafeProtectedBroadcastReceiver")
@OptIn(DelicateCoroutinesApi::class)

override fun onReceive(context: Context, intent: Intent) {
    Log.d("BroadcastReceiver", "ACTION_AIRPLANE_MODE_CHANGED")
    val isAirplaneModeEnabled = intent.getBooleanExtra("state", false)
    if (!isAirplaneModeEnabled) {
        goAsync(GlobalScope, Dispatchers.Default) {
            httpRequest()
        }
    }
}
private fun BroadcastReceiver.goAsync(
    coroutineScope: CoroutineScope,
    dispatcher: CoroutineDispatcher,
    block: suspend () -> Unit
) {
    val pendingResult = goAsync()
    coroutineScope.launch(dispatcher) {
        block()
        pendingResult.finish()
    }
}

private suspend fun httpRequest() {
    //        The request will not be fulfilled because we will not be able to connect to the network in time when flight mode is turned off. But that doesn't change the problem.
    val client = HttpClient(CIO) {
        expectSuccess = true

        install(HttpTimeout) {
            requestTimeoutMillis = 3000
        }
    }

    try {
        val response: HttpResponse = client.post("https://webhook.site") {
            setBody("hello")
        }
        Log.d("response", response.status.toString())
    } catch (e: Exception) {
        Log.d("PostRequest", e.toString())
    }
    client.close()
}

}

这是一个示例代码,乍一看似乎可以工作。但是,如果我连续多次打开和关闭飞行模式,我的广播接收器就会停止工作。仅当应用程序不在前台时才会发生这种情况。

goAsync 内的所有工作都在 1-2 秒内完成。我不明白为什么系统禁用我的 BroadcastReceiver

基于https://developer.android.com/develop/background-work/background-tasks#event-driven,我的方法似乎是正确的,但我可能遗漏了一些东西

android broadcastreceiver android-broadcast
1个回答
0
投票

该广播不是您可以在后台收听的列出的广播例外之一。

这意味着您可以收听此广播的唯一方法是当您的应用程序位于前台时

© www.soinside.com 2019 - 2024. All rights reserved.