I have figured out how to send and receive SMS messages. To send SMS messages I had to call the sendTextMessage()
and sendMultipartTextMessage()
m
SmsListenerClass
public class SmsListener extends BroadcastReceiver {
static final String ACTION =
"android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
Log.e("RECEIVED", ":-:-" + "SMS_ARRIVED");
// TODO Auto-generated method stub
if (intent.getAction().equals(ACTION)) {
Log.e("RECEIVED", ":-" + "SMS_ARRIVED");
StringBuilder buf = new StringBuilder();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
SmsMessage message = null;
for (int i = 0; i < messages.length; i++) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String format = bundle.getString("format");
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
} else {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
message = messages[i];
buf.append("Received SMS from ");
buf.append(message.getDisplayOriginatingAddress());
buf.append(" - ");
buf.append(message.getDisplayMessageBody());
}
MainActivity inst = MainActivity.instance();
inst.updateList(message.getDisplayOriginatingAddress(),message.getDisplayMessageBody());
}
Log.e("RECEIVED:", ":" + buf.toString());
Toast.makeText(context, "RECEIVED SMS FROM :" + buf.toString(), Toast.LENGTH_LONG).show();
}
}
Activity
@Override
public void onStart() {
super.onStart();
inst = this;
}
public static MainActivity instance() {
return inst;
}
public void updateList(final String msg_from, String msg_body) {
tvMessage.setText(msg_from + " :- " + msg_body);
sendSMSMessage(msg_from, msg_body);
}
protected void sendSMSMessage(String phoneNo, String message) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
Manifest