簡體   English   中英

從使用協程進行網絡調用的服務內部發送廣播

[英]sendBroadcast from inside Service which uses Coroutine for network call

我有一個 JobIntentService 應該執行 API 調用並在結果可用后進行廣播。

我正在使用協程使用 Retrofit 進行網絡調用。 但是,如果我在 CoroutineScope 內發送廣播,它不會觸發 BroadcastReceiver

這是我的服務代碼 -

我的服務.kt

class MyService : JobIntentService() {

    private val TAG = MyService::class.java.simpleName
    private var databaseHelper: DatabaseHelper = DatabaseHelper(this)
    private var imageFetcher: ImageFetcher = ImageFetcher(this)
    private var imageSaver: ImageSaver = ImageSaver(this)
    private val receiver = ServiceBroadcastReceiver()


    override fun onHandleWork(intent: Intent) {
        val filter = IntentFilter()
        filter.addAction("ACTION_FINISHED_SERVICE")
        registerReceiver(receiver, filter)

        when (intent.action) {
            "ACTION_FETCH_FROM_API" -> {
                handleFetchFromAPI()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)
    }

    private fun handleFetchFromAPI() {
        val API = ServiceBuilder.buildWebService(WebService::class.java)
        CoroutineScope(IO).launch {
            try {
                var apiSuccess : Boolean = false
                val apiResponse = API.getImageOfTheDay()
                if (apiResponse.isSuccessful) {
                    apiSuccess = true
                    val imageAPIResponse = apiResponse.body()
                    val bitmap = imageFetcher.getImageBitmapFromURL(imageAPIResponse.url)
                    val filePath = imageSaver.saveBitmapToFile(bitmap, "image.jpg")
                    withContext(Main) {
                        databaseHelper.saveImageInRoom(imageAPIResponse, filePath)
                    }
                }
                if(apiSuccess){
                    val broadCastIntent = Intent()
                    broadCastIntent.action = "ACTION_FINISHED_SERVICE"
                    sendBroadcast(broadCastIntent)
                } 
            } catch (exception: Exception) {
                Log.d(TAG, "Exception occurred ${exception.message}")
            }
        }
    }

    companion object {
        private const val JOB_ID = 2
        @JvmStatic
        fun enqueueWork(context: Context, intent: Intent) {
            enqueueWork(context, MyService::class.java, JOB_ID, intent)
        }
    }
}

ServiceBroadcastReceiver.kt class ServiceBroadcastReceiver: BroadcastReceiver() {

private val TAG = ServiceBroadcastReceiver::class.java.simpleName
private lateinit var _mNotificationManager: NotificationManager
private val _notificationId = 0
private val _primaryChannelId = "primary_notification_channel"

override fun onReceive(context: Context, intent: Intent) {
    _mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    when (intent.action) {
        "ACTION_FINISHED_SERVICE" -> {
            deliverNotification(context)
        }
    }
}

private fun deliverNotification(context: Context) {
    val contentIntent = Intent(context, MainActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(context,_notificationId,contentIntent,
            PendingIntent.FLAG_UPDATE_CURRENT)
    val builder = NotificationCompat.Builder(context,_primaryChannelId)
    builder.setSmallIcon(R.mipmap.ic_launcher)
    builder.setContentTitle("Hi There")
    builder.setContentText("Service finished its job")
    builder.setContentIntent(pendingIntent)
    builder.priority = NotificationCompat.PRIORITY_HIGH
    builder.setAutoCancel(true)
    builder.setDefaults(NotificationCompat.DEFAULT_ALL)
    _mNotificationManager.notify(_notificationId,builder.build())
}

}

getImageOfTheDay() 是 WebService.kt 中的暫停 function

@Headers("Content-Type: application/json")
@GET("/v1/getImageOfTheDay")
suspend fun getImageOfTheDay(): Response<ImageAPIResponse>

如果我將代碼移到協程 scope 之外,廣播將正確發送。 我該如何解決這個問題?

你不應該在這里使用協程。 onHandleWork方法在后台線程上調用,從該方法返回表示工作已完成並且可以終止服務。

當您使用launch啟動協程時, onHandleWork立即返回並且您的服務終止。

您應該直接而不是在協程中調用您的網絡 API,因為JobIntentService已經設計為以這種方式工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM