gpt4 book ai didi

如果消息已成功传递或发送,Android 短信会收到响应错误/通知

转载 作者:行者123 更新时间:2023-11-29 21:10:56 25 4
gpt4 key购买 nike

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();
}

最佳答案

你不能catch发送或交付成功/失败,因为它不是 Exception ,也不是任何其他类型的 Throwable .

您将需要创建 PendingIntent s 用于已发送已发送 操作,并在用于发送 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得到结果。一个基本的接收器示例:

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 s 将永远开火。

可以使用 Context#registerReceiver() 动态注册此 Receiver 的实例方法,或者可以使用 <receiver> 在 list 中注册 Receiver 类元素,以及适当的 <intent-filter>

关于如果消息已成功传递或发送,Android 短信会收到响应错误/通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22890415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com