我正在开发一些Android应用程序,它通过Web服务获取一组SMSes并发送它们,它作为服务实现,并且每2分钟调用一次,例如,通过LogCat,我可以看到消息被检索并与之一起发送sendTextMessage正常,但在手机上它不能一直工作,我敢肯定他们从服务器接到电话,但显然sendTextMessage和sendMultipartTextMessage不起作用,例如当它收到4条短信发送时它只发送一个或两个他们或有时没有,它随机播放,你看到我的问题在哪里吗?
服务:
public class CopyOfSender extends Service {
static final String KEY_ITEM_SMSList = "SMS";
static final String KEY_Id = "Id";
static final String KEY_Message = "Message";
static final String KEY_Number = "Number";
String SmsURL = "GetSMS/";
String UpdateMessageStatuseURL = "UpdateSMSStatus";
ConnectionDetector cd;
String userNumner = "";
String password = "";
String smsPerSend = "20";
Context thisContext = null;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
thisContext = getApplicationContext();
PowerManager pm = (PowerManager) getApplicationContext()
.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "");
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
if (pref.getString("smsPerSend", null) != null) {
smsPerSend = pref.getString("smsPerSend", "");
}
cd = new ConnectionDetector(getApplicationContext());
String BaseUrl = getApplicationContext().getResources().getString(
R.string.baseURl);
SmsURL = BaseUrl + SmsURL;
UpdateMessageStatuseURL = BaseUrl + UpdateMessageStatuseURL;
wl.acquire();
if (pref.getString("phonenumber", null) == null
|| pref.getString("password", null) == null) {
} else {
userNumner = pref.getString("phonenumber", "");
password = pref.getString("password", "");
if (!cd.isConnectingToInternet()) {
Toast.makeText(getApplicationContext(),
getApplicationContext().getString(R.string.noInternet),
Toast.LENGTH_LONG).show();
} else {
new SendSMS().execute();
}
}
wl.release();
}
private class Message {
public String Id;
public String Message;
public String Number;
}
private class SendSMS extends AsyncTask<Object, Object, Object> {
List<Message> messages = new ArrayList<Message>();
@Override
protected Object doInBackground(Object... arg0) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(SmsURL + "?number=" + userNumner
+ "&password=" + password + "&count=" + smsPerSend);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_ITEM_SMSList);
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
String tempId = parser.getValue(e, KEY_Id);
String tempMessage = parser.getValue(e, KEY_Message);
String tempNumber = parser.getValue(e, KEY_Number);
Message tempSMS = new Message();
tempSMS.Id = tempId;
tempSMS.Message = tempMessage;
tempSMS.Number = tempNumber;
messages.add(tempSMS);
}
for (Message item : messages) {
if (item.Number.trim().length() != 0) {
if (item.Message.trim().length() != 0) {
sendSMS(item.Number.trim(), item.Message.trim(),
Integer.parseInt(item.Id));
}
}
}
return null;
}
protected void onPostExecute(Object result) {
return;
}
}
private class UpdateSMSStat extends AsyncTask<Object, Object, Object> {
@Override
protected Object doInBackground(Object... arg0) {
int smsId = (Integer) arg0[0];
int stat = (Integer) arg0[1];
XMLParser parser = new XMLParser();
List<NameValuePair> IdsToSend = new ArrayList<NameValuePair>();
IdsToSend.add(new BasicNameValuePair("MessageIds", Integer
.toString(smsId)));
IdsToSend.add(new BasicNameValuePair("Status", Integer
.toString(stat)));
IdsToSend.add(new BasicNameValuePair("Number", userNumner));
IdsToSend.add(new BasicNameValuePair("Password", password));
parser.sendPostRequest(UpdateMessageStatuseURL, IdsToSend);
return null;
}
}
private void sendSMS(final String phoneNumber, String message,
final int messageId) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(thisContext, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(thisContext, 0,
new Intent(DELIVERED), 0);
thisContext.registerReceiver(new BroadcastReceiver() {
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));
thisContext.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
new UpdateSMSStat().execute(messageId, 1, phoneNumber);
break;
case Activity.RESULT_CANCELED:
new UpdateSMSStat().execute(messageId, 3, phoneNumber);
break;
}
}
}, new IntentFilter(DELIVERED));
Pattern p = Pattern
.compile("[^a-zA-Z0-9!@#$%^&*()_+-=\\|`~{};':,.<>/?/[/]\" ]");
boolean hasSpecialChar = p.matcher(message).find();
SmsManager sms = SmsManager.getDefault();
if (hasSpecialChar) {
if (message.length() > 70) {
ArrayList<String> parts = sms.divideMessage(message);
ArrayList<PendingIntent> sentPis = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> deliverPis = new ArrayList<PendingIntent>();
sentPis.add(sentPI);
deliverPis.add(deliveredPI);
sms.sendMultipartTextMessage(phoneNumber, null, parts, sentPis,
deliverPis);
} else {
sms.sendTextMessage(phoneNumber, null, message.toString(),
sentPI, deliveredPI);
}
} else {
if (message.length() > 160) {
ArrayList<String> parts = sms.divideMessage(message);
ArrayList<PendingIntent> sentPis = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> deliverPis = new ArrayList<PendingIntent>();
sentPis.add(sentPI);
deliverPis.add(deliveredPI);
sms.sendMultipartTextMessage(phoneNumber, null, parts, sentPis,
deliverPis);
} else {
sms.sendTextMessage(phoneNumber, null, message.toString(),
sentPI, deliveredPI);
}
}
}
}
答案 0 :(得分:0)
试试这个,
private int mMessageSentParts;
private int mMessageSentTotalParts;
private int mMessageSentCount;
private void startSendMessages(){
registerBroadCastReceivers();
mMessageSentCount = 0;
sendSMS(array[mMessageSentCount].toString(), message);
}
private void sendNextMessage(){
if(thereAreSmsToSend()){
sendSMS(array[mMessageSentCount].toString(), message);
}else{
Toast.makeText(getBaseContext(), "All SMS have been sent",
Toast.LENGTH_SHORT).show();
}
}
private boolean thereAreSmsToSend(){
return mMessageSentCount < array.length;
}
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);
mMessageSentTotalParts = parts.size();
Log.i("Message Count", "Message Count: " + mMessageSentTotalParts);
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 < mMessageSentTotalParts; j++) {
sentIntents.add(sentPI);
deliveryIntents.add(deliveredPI);
}
mMessageSentParts = 0;
sms.sendMultipartTextMessage(phoneNumber, null, parts, sentIntents, deliveryIntents);
}
private void registerBroadCastReceivers(){
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
mMessageSentParts++;
if ( mMessageSentParts == mMessageSentTotalParts ) {
mMessageSentCount++;
sendNextMessage();
}
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));
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));
}
答案 1 :(得分:0)
我在使用openfire服务器的xmpp协议的聊天应用程序(smack)中遇到了同样的问题。我解决了。
如果您的SMS使用与服务器的连接。我认为你有连接问题。您应该在消息发送时创建 Bucket ,如: -
sendMessage(message)
{
try
{
// your message send code
}
catch(Exception e)
{
// save your message in a local DB.
}
}
所以当Connection 重新连接到服务器时,它会发送所有存储桶消息,如
connection.connect();
// here check to bucket.
// if there is any message
// send all message
// and delete all bucket message.
// else if there is not any message in bucket.
// then bucket is empty so no message need to send.
请遵循此逻辑。你的信息永远不会丢失。
也可能是模拟器连接是有线连接,因此连接不会总是丢失并发送所有消息。
真正的Android设备可能会因网络问题或其他原因而丢失连接。大多数情况下在Wifi。和服务重新启动。
谢谢!
答案 2 :(得分:0)
很可能你只需要在sendSMS()调用之间有一个延迟:
for (Message item : messages) {
if (item.Number.trim().length() != 0) {
if (item.Message.trim().length() != 0) {
sendSMS(item.Number.trim(), item.Message.trim(),
Integer.parseInt(item.Id));
try {
Thread.sleep(SOME_DELAY);
}
catch(Exception e) { }
}
}
}
或者如果您想要更准确,那么您可以等待SENT广播,然后发送另一条短信。