package com.androidsmsgateway.sms import android.app.Activity import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.telephony.SmsManager import com.androidsmsgateway.GatewayApplication import com.androidsmsgateway.domain.MessageStatus import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class SmsStatusReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action != ACTION_SENT) return val id = intent.getStringExtra(EXTRA_MESSAGE_ID) ?: return val pendingResult = goAsync() val repository = (context.applicationContext as GatewayApplication).container.gatewayRepository val result = resultCode val succeeded = isSuccessfulResult(result) CoroutineScope(Dispatchers.IO).launch { try { runCatching { repository.outgoingById(id)?.let { message -> repository.updateOutgoing( message.copy( status = if (succeeded) MessageStatus.SENT.name else MessageStatus.FAILED.name, errorCode = if (succeeded) null else "ANDROID_SMS_ERROR_$result", updatedAt = System.currentTimeMillis(), ), ) } } } finally { pendingResult.finish() } } } companion object { const val ACTION_SENT = "com.androidsmsgateway.SMS_SENT" const val EXTRA_MESSAGE_ID = "message_id" internal fun isSuccessfulResult(resultCode: Int): Boolean = resultCode == Activity.RESULT_OK || resultCode == SmsManager.RESULT_ERROR_NONE } }