Check if an SMS is actually sent

本秂侑毒 提交于 2019-12-20 15:24:07

问题


In my SMS application I am sending SMSes using an SmsManager. After that I want to display a Toast saying "Message sent" or "Message not sent". How could I check if the message was actually sent? Could be like a no connection issue? or no SIM? How could I detect these?


回答1:


you can set listeners for both for delievery and sending my method is

PendingIntent sentPI = PendingIntent.getBroadcast(mContext, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(mContext, 0,new Intent(DELIVERED), 0);
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";


// ---when the SMS has been sent---
        mContext.registerReceiver(
                new BroadcastReceiver()
                {    
                    @Override
                    public void onReceive(Context arg0,Intent arg1)
                    {
                        switch(getResultCode())
                        {
                    case Activity.RESULT_OK:

                            break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:

                            break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                            break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                            break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                            break;
                        }
                    }
                }, new IntentFilter(SENT));
        // ---when the SMS has been delivered---
        mContext.registerReceiver(
                new BroadcastReceiver()
                {

                    @Override
                    public void onReceive(Context arg0,Intent arg1)
                    {
                        switch(getResultCode())
                        {
                        case Activity.RESULT_OK:
                            break;
                        case Activity.RESULT_CANCELED:
                            break;
                        }
                    }
                }, new IntentFilter(DELIVERED));


SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null,message,sentPI, deliveredPI);



回答2:


Try below snippet. Here exception indicates the all possible failure case

Snippet

try {
      SmsManager smsManager = SmsManager.getDefault();
      smsManager.sendTextMessage(number, null, sms, null, null);
      Toast.makeText(getApplicationContext(), "SMS Sent!",
                            Toast.LENGTH_LONG).show();
 } catch (Exception e) {
        Toast.makeText(getApplicationContext(), "SMS failed, please try again later!",
               Toast.LENGTH_LONG).show();
         e.printStackTrace();
}

Check out an example here



来源:https://stackoverflow.com/questions/18771356/check-if-an-sms-is-actually-sent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!