我目前正在尝试开发一个 SMS 应用程序并允许用户向多个人发送 SMS。
由于短信很长,我必须使用下面的 sendMultipartTextMessage
private void sendSMS(final String phoneNumber, String message) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
SmsManager sms = SmsManager.getDefault();
ArrayList<String> parts = sms.divideMessage(message);
int messageCount = parts.size();
Log.i("Message Count", "Message Count: " + messageCount);
ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
for (int j = 0; j < messageCount; j++) {
sentIntents.add(sentPI);
deliveryIntents.add(deliveredPI);
}
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
// ---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
sms.sendMultipartTextMessage(phoneNumber, null, parts, sentIntents, deliveryIntents);
}
当我尝试在这样的循环中将它发送给多个人并且不会发送消息时,我会遇到一般错误。我怀疑这是因为消息可能是 3-4 部分,即使有 3000 毫秒的延迟,android 系统也无法及时发送消息。
for (int t = 0; t < array.length; t++) {
System.out.println("temp: " + array[t].toString());
try {
sendSMS(array[t].toString(), message);
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
编辑:上面的代码在一个 AsyncTask 中,它在一个服务中执行。