问题
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