Send SMS on Android
I made a java class to send sms but I have a problem when I call the class more than once in the same service.
The messages are sent perfect, but as you can see in my class I have a PendingIntent listening when sending the messages and their status (whether successfully or there was error).
The problem is:
if I call twice to the same class, those two times the BroadcastReceiver receives the same message.
For example: if I call twice a class, and one of the shipments has an error. The two BroadcastReceiver receive the same error, or both receive as if it was actually successfully but one had an error.
I searched all morning but have not found the solution. I hope someone knows where I'm wrong :)
// imports....
public class SendSms {
public SmsNoticeListener mListener;
private UserGroupRead user;
public interface SmsNoticeListener {
public void onSentReceiver(UserGroupRead user, int resultcode);
public void onDeliveredReceiver(UserGroupRead user, int resultcode);
}
private Context context;
private String phoneNumber;
private String message;
private BroadcastReceiver sendBroadcastReceiver;
private BroadcastReceiver deliveryBroadcastReceiver;
public SendSms(Context context, SmsNoticeListener mListener, UserGroupRead user, String phoneNumber, String message) {
this.context = context;
this.mListener = mListener;
this.user = user;
this.phoneNumber = phoneNumber;
this.message = message;
}
public void send() {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent(DELIVERED), 0);
sendBroadcastReceiver = new BroadcastReceiver(){
public void onReceive(Context arg0, Intent arg1) {
mListener.onSentReceiver(user, getResultCode());
}
};
context.registerReceiver(sendBroadcastReceiver, new IntentFilter(SENT));
deliveryBroadcastReceiver = new BroadcastReceiver(){
public void onReceive(Context arg0, Intent arg1) {
mListener.onDeliveredReceiver(user, getResultCode());
}
};
context.registerReceiver(deliveryBroadcastReceiver, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
public void close() {
context.unregisterReceiver(sendBroadcastReceiver);
context.unregisterReceiver(deliveryBroadcastReceiver);
}
}
链接地址: http://www.djcxy.com/p/63376.html
上一篇: Activity和BroadcastReceiver中的Timer.schedule不同
下一篇: 在Android上发送短信
