How can i get the error when sending message and the response when the message has been successfully sent?
这是我的代码:
try {
String message = "Hello World! Now we are going to demonstrate " +
"how to send a \n message with more than \n 160 characters from your Android application.";
SmsManager smsManager = SmsManager.getDefault();
ArrayList<String> parts = smsManager.divideMessage(message );
smsManager.sendMultipartTextMessage(phoneNumber, null, parts, null, null);
} catch (Exception e) {
//HOW CAN I GET THE SMS RESPONES HERE
Toast.makeText(context, "SMS faild!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
答案 0 :(得分:2)
您不能catch
发送或传递成功/失败,因为它不是Exception
,也不能是Throwable
的任何其他类型。
您需要为已发送的和已发送的操作创建PendingIntent
,并使用用于发送SMS的方法传递它们。以下是可用于单个或多个部分消息的示例。
public static final String ACTION_SMS_SENT = "com.mycompany.myapp.SMS_SENT";
public static final String ACTION_SMS_DELIVERED = "com.mycompany.myapp.SMS_DELIVERED";
private void sendSMS(String number, String message) {
final SmsManager sm = SmsManager.getDefault();
final ArrayList<String> parts = sm.divideMessage(message);
final int ct = parts.size();
final ArrayList<PendingIntent> sentPis = new ArrayList<PendingIntent>(ct);
final ArrayList<PendingIntent> delPis = new ArrayList<PendingIntent>(ct);
for (int i = 0; i < ct; i++) {
final PendingIntent piSent =
PendingIntent.getBroadcast(this,
i,
new Intent(ACTION_SMS_SENT),
0);
final PendingIntent piDel =
PendingIntent.getBroadcast(this,
i,
new Intent(ACTION_SMS_DELIVERED),
0);
sentPis.add(piSent);
delPis.add(piDel);
}
sm.sendMultipartTextMessage(number, null, parts, sentPis, delPis);
}
您需要注册BroadcastReceiver
才能获得结果。一个基本的Receiver示例:
public class SmsResultReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ACTION_SMS_SENT)) {
switch (getResultCode()) {
case -1: //Activity.RESULT_OK
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
break;
default:
}
}
else if (action.equals(ACTION_SMS_DELIVERED)) {
switch (getResultCode()) {
case -1: //Activity.RESULT_OK
break;
case 0: //Activity.RESULT_CANCELED
break;
default:
}
}
}
}
请注意,每个Receiver将针对每个消息部分运行一次。我还要提到并非所有运营商都提供递送报告,因此无法保证已发送 PendingIntent
将会触发。
可以使用Context#registerReceiver()
方法动态注册此Receiver的实例,或者可以使用<receiver>
元素和相应的<intent-filter>
s在清单中注册Receiver类。