Skip to content

Instantly share code, notes, and snippets.

@ceosilvajr
Created June 4, 2015 08:26
Show Gist options
  • Save ceosilvajr/83693fac3d7f7ba6e411 to your computer and use it in GitHub Desktop.
Save ceosilvajr/83693fac3d7f7ba6e411 to your computer and use it in GitHub Desktop.
Android SMSHelper
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.util.Log;
/**
* Created by ceosilvajr on 6/4/15.
*/
public class SMSHelper {
private static final String TAG = "SMSHelper";
private Activity mActivity;
private SMSCallBack mSMSmsCallBack;
public SMSHelper(Activity mActivity, SMSCallBack smsCallBack) {
this.mActivity = mActivity;
this.mSMSmsCallBack = smsCallBack;
}
public void sendMessage(String receipient, String message) {
mSMSmsCallBack.onStart();
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(mActivity, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(mActivity, 0,
new Intent(DELIVERED), 0);
mActivity.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
mSMSmsCallBack.onFinish();
if (getResultCode() == Activity.RESULT_OK) {
Log.d(TAG, "SMS sent");
mSMSmsCallBack.onSent();
return;
}
switch (getResultCode()) {
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
mSMSmsCallBack.onError("Generic Failure");
Log.d(TAG, "Generic failure");
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
mSMSmsCallBack.onError("No service");
Log.d(TAG, "No service");
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
mSMSmsCallBack.onError("Null PDU");
Log.d(TAG, "Null PDU");
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
mSMSmsCallBack.onError("Radio off");
Log.d(TAG, "Radio off");
break;
default:
mSMSmsCallBack.onError("Failed to sent your request.");
break;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered---
mActivity.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Log.d(TAG, "SMS delivered");
mSMSmsCallBack.onMessageDelivered();
break;
case Activity.RESULT_CANCELED:
Log.d(TAG, "SMS not delivered");
mSMSmsCallBack.onMessageNotDelivered();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(receipient, null, message, sentPI, deliveredPI);
}
public interface SMSCallBack {
void onStart();
void onFinish();
void onError(String message);
void onSent();
void onMessageDelivered();
void onMessageNotDelivered();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment