如何知道短信在Android中正确发送?

问题描述

我正在制作短信管理器应用程序。 这是我的代码

接收方代码

private val receiver = object : broadcastReceiver() {
    override fun onReceive(context: Context?,intent: Intent) {
        val id = intent.getIntExtra("id",0)
        if (resultCode == Activity.RESULT_OK) {
            Log.d("SMS","Success to sent SMS")
        } else {
            Log.e("SMS","Failed to send SMS")
        }
    }
}

发送短信方法

private fun sendMessage(phone: String,message: String) {
    try {
        Log.d("SMS","Send SMS")
        val intent = Intent(SENT)
        val sentIntent = PendingIntent.getbroadcast(activity,intent,PendingIntent.FLAG_ONE_SHOT)
        smsManager.sendTextMessage(phone,null,message,sentIntent,null)
    } catch (ex: Exception) {
        Log.e("Error","error",ex)
    }
}

当我向正确的号码发送消息时,接收者可以收到“成功”事件。挺好的!
但是当我将消息发送到诸如“123123123”之类的随机数时,接收方也会收到“成功”事件。这糟糕!
所以我检查了我的手机,但在认消息应用程序中有失败的消息。

所以我的问题是:
为什么在我的代码的 sentIntent 中广播 success event
我该如何解决这个问题?

请任何人帮助我。
谢谢。

附注。 我已经看过以下网址。但仍然没有答案。

sms is always display "sms sent" even when using random cellphone number without delivery reports - android

Android sms is always sent same contact

How to test sms sending failure in emulator

解决方法

SENT 状态仅反映短信从手机到陆侧 SMSC(服务器)的传输。当您获得 SUCCESS 时,这意味着消息已成功从手机传输到服务器。它与将消息实际传递给收件人没有任何关系。

如果您想了解递送状态,您需要创建一个额外的 PendingIntent 并将其传递给 SmsManager

    val intent = Intent(SENT)
    val sentIntent = PendingIntent.getBroadcast(activity,intent,PendingIntent.FLAG_ONE_SHOT)
    val intent2 = Intent(DELIVERY)
    PendingIntent.getBroadcast(activity,intent2,PendingIntent.FLAG_ONE_SHOT)
    smsManager.sendTextMessage(phone,null,message,sentIntent,deliveryIntent)

然后您的 BroadcastReceiver 可以捕获递送 Intent 并确定消息是否已成功递送。