Situation:
I have a Service
(also have tried using anActivity
) that sends SMS messages on each button click. I'm 99.9% certain the method sendSMS(...)
is getting called only once. Toasts
that are created within the BroadcastReceiver
stay on the screen from anywhere between a few seconds and almost in defiantly, until app is forced stop. "SMS Sent"
is stuck on the screen for a period of time and the SMS sends successfully. You can see the Toast
fade in and out a little bit.
Am I doing something wrong?
Bonus:
Why doesn't the BroadcastReceiver
with the "SMS delivered"
status ever get any responses?
Here's the very Generic code I grabbed from a tutorial long ago:
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
sendSMS("5555555","hello world");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
sendSMS("5555555","hello world");
return Service.START_STICKY;
}
// ---sends an SMS message to another device---
private void sendSMS(final String phoneNumber, final String message) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this.getApplicationContext(), 0, new Intent(
SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this.getApplicationContext(), 0,
new Intent(DELIVERED), 0);
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(context, "SMS error: Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(context, "SMS error: No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(context, "SMS error: Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(context, "SMS error: Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
// ---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(context, "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
/Edit: fixed the problem as you can read in the comments of this question