Reputation: 377
I'm trying to create an app on android where I need to display messages in a chat like fashion. I've been reading on the 4.4 API for SMS and I cant seem to figure out how to use those. Currently, I am only getting the received messages from sms.Inbox Content Provider. Can someone point me to where I can see some examples on how to make use of them efficiently?
Upvotes: 2
Views: 462
Reputation: 604
Use BroadcastReceiver
to get broadcast when a SMS will be received by the phone, as shown below:
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras == null)
return;
// To display a Toast whenever there is an SMS.
// Toast.makeText(context,"Recieved",Toast.LENGTH_LONG).show();
Object[] pdus = (Object[]) extras.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage SMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = SMessage.getOriginatingAddress();
String body = SMessage.getMessageBody().toString();
// A custom Intent that will used as another Broadcast
Intent in = new Intent("SmsMessage.intent.MAIN").putExtra(
"get_msg", sender + ":" + body);
// You can place your check conditions here(on the SMS or the
// sender)
// and then send another broadcast
context.sendBroadcast(in);
// This is used to abort the broadcast and can be used to silently
// process incoming message and prevent it from further being
// broadcasted. Avoid this, as this is not the way to program an
// app.
// this.abortBroadcast();
}
}
Upvotes: 1