http://mobiforge.com/developing/story/sms-messaging-android
我在上面的链接中使用了我自己的应用程序发送短信的示例代码,但是在检查我的消息的发送状态时遇到了问题。发生的事情是,我试图发送的每条消息都会弹出Toast消息。所以基本上,假设我已经发送了3条消息。当我发送第4条消息时,Toast消息将弹出4次。似乎BroadcastReceiver可能从目前使用的每个意图接收相同的广播?我无法弄清楚为什么会发生这种情况,或者如何阻止它。任何帮助或见解将不胜感激!
以下是导致此问题的具体方法:
//---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String 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), 0);
//---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));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
答案 0 :(得分:8)
首先,每次拨打new BroadcastReceiver(){
时都会有sendSMS
,所以每次拨打sendSMS
时,他们会堆积一次。{1}}。您可以在每个unregister(this);
的底部添加BroadcastReceiver
,但更好的方法是将广播接收器移出此功能。您可以onResume()
中的创建+注册,unregister
中的onPause().
其次,请阅读此link
如果您想与pendingIntent
一起发送数据,则需要帮助Android更好地区分您的待定意图... 例如
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, uniqueIdPerSMS++,
new Intent(DELIVERED), PendingIntent.FLAG_CANCEL_CURRENT);
答案 1 :(得分:0)
这很简单就是为每个deliverPI使用一个唯一的id,因为如果不这样,那么android会认为所有相同的所有sms的deliverPi都会显示任何一个的结果(不知道是第一个还是最后一个)