I use the following code to send an SMS. The problem is that the application indicates that the message has been sent correctly, but it is not actually sent or appears in the list of sent SMS, and I can't find where the problem could be.
public void enviar(String numTelefono, String mensaje) {
if (mensaje.length() > 160) {
Toast.makeText(context, R.string.sms_limite_max, Toast.LENGTH_LONG).show();
return;
}
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
try {
SmsManager smsMgrVar = SmsManager.getDefault();
smsMgrVar.sendTextMessage(numTelefono, null, mensaje, null, null);
Toast.makeText(context, R.string.sms_ok,
Toast.LENGTH_LONG).show();
} catch (Exception error) {
Toast.makeText(context, error.getMessage().toString(),
Toast.LENGTH_LONG).show();
error.printStackTrace();
}
} else {
Toast.makeText(context, R.string.sms_sin_permiso,
Toast.LENGTH_LONG).show();
}
}
The code you show is correct, but consider that in order to send SMS messages you must meet these points :
• The device from where you want to send the message must have telephone support.
• You must define the permission
SEND_SMS
both within the AndroidManifest.xml and make the request manually, you can see more information:Permissions to send Text Messages (send SMS)
• You must use the SmsManager class which supports GSM and CDMA.
• Correctly define the number and message.
Example:
Try adding a PendingIntent
What you are doing is printing the Toast after
sendTextMessage()
so if the caller does not throw an IllegalArgumentException you will always display the success message.By using PendingIntent you can tell if the message was sent successfully or failed. So after executing you
sendTextMessage()
can know the resulting code and only show your Toast if it is the sameActivity.RESULT_OK
.The specification of the different error messages can be found here