【发布时间】:2014-07-28 13:43:10
【问题描述】:
我正在开发一个应用程序,我在其中发送短信,我需要查看它是否已送达。 如果我向某人发送消息,一切似乎都很好。
但是在某些情况下我得到了错误的信息,例如,首先我向号码 0000 发送一条消息(但它不会发送),然后我向号码 0001 发送一条消息并且它发送(发送到 0000 的消息仍然没有已交付)但我得到了一个祝酒词:短信已发送到 0000(但仅发送到 0001 的消息),我应该如何解决传递报告中的此冲突?
这是我的代码:
try {
SmsManager smsManager = SmsManager.getDefault();
String to = "5556";
String body = "Test Message";
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED).putExtra("senderNumber", to), 0);
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(arg0, "SMS sent", Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(arg0, "Error", Toast.LENGTH_LONG).show();
break;
}
}
}, new IntentFilter(SENT));
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
String s = arg1.getStringExtra("senderNumber");
Toast.makeText(getBaseContext(), "SMS delivered to " + s, Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_LONG).show();
break;
}
}
}, new IntentFilter(DELIVERED));
smsManager.sendTextMessage(to.getText().toString(), null, body.getText().toString(), sentPI, deliveredPI);
}
catch (Exception ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}
更新:
我发现如果我在 Intent 操作中添加一个唯一的 id (DELIVERED+id) 就可以了,不会发生冲突。 但我没有在创建消息时注册接收器,我使用清单文件来执行此操作:
<receiver android:name=".SendBroadcastReceiver" >
<intent-filter>
<action android:name="com.example.myapp.SMS_SENT" />
<action android:name="com.example.myapp.SMS_DELIVERED" />
</intent-filter>
</receiver>
还有一个名为 SendBroadcastReceiver 的 Receiver 类来处理短信发送。
如果我为 action 添加一个唯一的 id,我如何将它们添加到清单文件中?
【问题讨论】:
-
您希望保持操作不变,但更改每个 PendingIntent 的请求代码。在这里查看我的答案:stackoverflow.com/questions/24673595/…。该示例动态注册 BroadcastReceiver,但忽略它。
-
@MikeM。像魅力一样工作,感谢您的帮助
标签: android android-pendingintent smsmanager