简体   繁体   中英

How to know SMS is correctly sent in Android?

I am making SMS Manager application. Here is my code.

Receiver Code:

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")
        }
    }
}

Send SMS method:

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

When I send message to correct number, the receiver can receive "Success" event. It's good!
But when I send message to random number such as "123123123", the receiver also receive "Success" event. It's bad!
So I checked in my phone, but there is failed message in default messaging app.

So my question is:
Why broadcast success event in sentIntent of my code?
How can I fix this problem?

Please anyone help me.
Thanks.

PS. I already looked following URLs. But there is still no answer.

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

The SENT status only reflects the transmission of the SMS from the phone to the land-side SMSC (Server). When you get SUCCESS this means that the message has successfully been transmitted from the phone to the server. It doesn't have anything to do with the actual delivery of the message to the recipient.

If you want to be informed about the status of the delivery, you need to create an additional PendingIntent and pass that to the SmsManager as well:

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

Your BroadcastReceiver can then catch the delivery Intent and determine if the message was sucessfully delivered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM