从IntentService发送短信?

时间:2015-09-15 12:32:32

标签: android sms intentservice

我想做以下事情:

  • 发送短信
  • 检查是否已发送
  • 如果它不是
  • ,则将其存储在SQLite实例中
  • 重新发送之前存储的所有短信。

所以你有一个主要的短信发送动作,需要对其状态的反馈(告诉用户是否可以发送),以及后台短信发送动作,只会尝试重新发送以前未发送的短信静默。

我提出的解决方案涉及一个IntentService,它有两个动作:

  • 发送短信。
  • 尝试发送以前存储的短信。

到目前为止一切都那么好,同样的事情对于向服务器发送TCP消息起了作用。现在的问题是,我似乎无法从IntentService发送短信。

想法是让IntentService创建一个PendingIntent,主要的Activity提供PendingIntent内部(这基本上就是告诉活动发送短信的回调),然后用它发送短信。

然后使用静态接收器获取PendingIntent并在IntentService上启动一个新操作,以便从SQLite实例中删除SMS(如果它已正确发送)。

这是IntentService中的主要消息发送方法:

private void sendMessage(Configuration cfg, SMSMessage msg, PendingIntent resultIntent) {
    final Intent smsIntent;
    // Select which kind of intent we're creating.
    if (resultIntent == null) {
        // This one is the silent background SMS.
        smsIntent = new Intent(this.getApplicationContext(), RedirectPendingMessages.class);
    } else {
        // This one is the one from the application.
        smsIntent = new Intent(this.getApplicationContext(), RedirectMessage.class);
        smsIntent.putExtra(EXTRA_PENDING_RESULT, resultIntent);
    }
    // Now store the message.
    smsIntent.putExtra(EXTRA_SMS, msg);
    // Construct broadcast intent.
    PendingIntent pi = PendingIntent.getBroadcast(this.getApplicationContext(), 0, smsIntent, 0);
    // Now send message.
    SmsManager smsMng = SmsManager.getDefault();
    smsMng.sendTextMessage(cfg.phoneNumberFor(msg.level), null, msg.content, pi, null);
}

进入' SmsManager.sendTextMessage'方法很好,但没有发生,即使我硬编码电话号码并且没有通过任何PendingIntent短信仍然没有被发送可能是因为IntentService在方法调用后不再存在?

接收方只需抓取广播的Intent,获取内部数据,然后在IntentService中启动适当的操作以删除已发送的SMS,并广播应用程序的PendingIntent,以便UI可以提供一些反馈给用户("短信已发送","错误"等)。

我对同一件事的TCP实现几乎只有一个Socket写入而不是那个' sendTextMessage',它会阻止IntentService直到它完成并且工作正常。

有关为什么不发送短信或如何更好地实施短信的任何想法?

1 个答案:

答案 0 :(得分:1)

您的邮件似乎超出了您正在使用的字母的字符数限制,这导致SmsManager#sendTextMessage()方法无声地失败。

对于基本的7位默认字母,字符限制为160;对于8位,它是140;对于16位,这听起来像你的情况,它是70,解释为什么你的120个字符的消息分为两部分。

如您所发现,您可以使用SmsManager#divideMessage()方法将邮件拆分为可用部分,并使用SmsManager#sendMultipartTextMessage()正确发送邮件。

SmsManager Reference

相关问题