我有一个程序,只需按一下按钮就可以向一组人发送预定义的文本消息。我的工作正常,但是我的问题是,当它发送消息时,每条消息都会弹出2个吐司。码:
package com.mfd.alerter;
//imports
public class homeScreen extends Activity {
//buttons
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//vars
// Grab the time
final Date anotherCurDate = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("km");
final String formattedTime = formatter.format(anotherCurDate);
// Contacts
final String[] numbers = getResources().getStringArray(R.array.numbers);
// Start messages. Only 1 is given to shorten post
callStructureFire.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String msgText = "MFD PAGE OUT:\nStructure Fire\nTimeout:"+formattedTime;
for (int i = 0; i < numbers.length; i++) {
sendSMS(numbers[i], msgText);
}
}
});
//more call types. not important.
}
//---sends a SMS message to another device---
private void sendSMS(String numbers, String message)
{
String SENT = "SMS_SENT";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 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));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(numbers, null, message, sentPI, null);
}
//action bar stuff. not important.
}
更详细:假设我将文本发送给3个人,将弹出6条吐司消息,提示“ SMS Sent”。我如何做到只有3个出现?
另外,是否有办法添加发送邮件的计数器?例如:“已发送消息1/10”,“已发送消息2/10”等?
最佳答案
您不应该只注册一次接收者,而不是每次调用sendSMS时都注册一次。
因为您有3个BroadCastReceivers,所以您收到6条带有3条短信的Toast。因此,在第一次运行中,您将获得1吐司。在第二轮中,您将获得2个Toasts(在第一轮中注册的接收器被调用,在第二轮中注册的接收器被调用)。在第三轮中,所有三个接收器都被调用,因此您又得到了三个吐司。总计-6敬酒...
所以我想,您只需在调用sendSMS的for循环之前注册一个接收者,或者如果您想在sendSMS中进行注册,则必须在方法末尾取消注册。
我希望这有帮助,
干杯!