Android C#:从Android服务发送短信

时间:2017-02-19 07:58:07

标签: android xamarin xamarin.android sms

我有使用Xamarin Studio编写的android服务,我正在尝试自动从此服务发送短信。对于发送,我使用以下代码:

SmsManager.Default.SendTextMessage("+7926736XXXX", null, "Simple Service sent you a message", null, null);

因此,短信没有发送到其他手机,但留在红色三角标记的短信列表中。我可以稍后用手发送它们没有任何问题。谁能知道我的错误在哪里?

3 个答案:

答案 0 :(得分:0)

试试这个,

SmsManager sms = SmsManager.getDefault();
PendingIntent sentPI;
String SENT = "SMS_SENT";

sentPI = PendingIntent.getBroadcast(this, 0,new Intent(SENT), 0);

sms.sendTextMessage("+7926736XXXX", null, message, sentPI, null);

OR 像这样的意图发送它

var smsUri = Android.Net.Uri.Parse("smsto:7926736XXXX");
var smsIntent = new Intent (Intent.ActionSendto, smsUri);
smsIntent.PutExtra ("sms_body", "Hello from Xamarin.Android");  
StartActivity (smsIntent);
希望这会有所帮助。

答案 1 :(得分:0)

尝试检查已发送和已发送的意图的SmsResultErrorSmsStatus,以确定您的短信无效的原因。

BroadcastReceiver内部课程添加到Service

public YourSMSService : Service
{
    const string SentAction = "SentAction";
    const string DeliveredAction = "DeliveredAction";
    SmsReceiver smsReceiver;

    ~~~~

    class SmsReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            if (intent.Action == SentAction)
            {
                // `Log` it if needed...
                Toast.MakeText(context, $"{(SmsResultError)ResultCode}", ToastLength.Long).Show();
            }
            if (intent.Action == DeliveredAction)
            {
                // `Log` it if needed...
                Toast.MakeText(context, $"{(SmsStatus)ResultCode}", ToastLength.Long).Show();
            }
        }
    }

    ~~~~
}

创建/注册BroadcastReceiver(通常在Service .actor中完成)

smsReceiver = new SmsReceiver();
RegisterReceiver(smsReceiver, new IntentFilter(SentAction));
RegisterReceiver(smsReceiver, new IntentFilter(DeliveredAction));

已将PendingIntent发送至SendTextMessage

var sentIntent = PendingIntent.GetBroadcast(this, 0, new Intent(SentAction), 0);
var deliveredIntent = PendingIntent.GetBroadcast(this, 0, new Intent(DeliveredAction), 0);
SmsManager.Default.SendTextMessage("1234567890", null, "Simple Service sent you a message", sentIntent, deliveredIntent);

现在,当您在服务中发送短信时,您将收到状态的Toast消息。

答案 2 :(得分:-1)

问题已经结束。这是我手机的硬件问题。我连接了10年前的中国三星Galaxy副本,我的应用程序立即开始工作