如何阻止我的应用程序多次显示Toast消息?每当我发送短信是否是一个,两个或更多联系人时,它总是多次显示吐司消息。有时吐司看起来好像在闪烁,同时显示“短信发送”信息大约2,4,18次。我认为它将“短信发送”的消息加倍。如果我将它发送到1号码,它会显示2,依此类推
try {
String message = "firealert";
String additionalMessage = send_input.getText().toString();
info.open();
ArrayList<String> data = info.getContactNumber();
info.close();
for(String contactNum : data)
{
sendSMS("0".concat(contactNum), message+" "+additionalMessage);
//sendSMS(contactNum, message+" "+additionalMessage);
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS failed, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
并使用此代码显示短信状态
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()
{
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 :(得分:0)
您可以做的是创建一个Toast变量。
private Toast t;
if(t!=null)
t.cancel();
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
OR
if(t==null)
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
答案 1 :(得分:0)
短信的内容是否超过160个字符?您是否有可能看到Toast(content.length()/ 160)次? 短信可能分为几个部分。