Today we learn how to detect new message arrive,and show that body and number through broadcast receiver.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.gsm.SmsMessage;
import com.parse.ParseObject;
public class SmsReciever extends BroadcastReceiver {
private String displayName = “”, ContactName = “”;
@SuppressWarnings(“deprecation”)
@Override
public void onReceive(Context context, Intent intent) {
System.out.println(“onReceive == ” + intent.getAction());
Bundle pudsBundle = intent.getExtras();
SmsMessage[] msgs = null;
String phonenumber = “”, str = “”;
if (pudsBundle != null) {
System.out.println(” on if “);
Object[] pdus = (Object[]) pudsBundle.get(“pdus”);
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
phonenumber = msgs[i].getOriginatingAddress();
System.out.println(“phone number =”+phonenumber);
str += msgs[i].getMessageBody().toString();
System.out.println(“str message=”+str);
// Resolving the contact name from the contacts.
Uri lookupUri = Uri.withAppendedPath(
PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phonenumber));
Cursor c = context
.getContentResolver()
.query(lookupUri,
new String[] { ContactsContract.Data.DISPLAY_NAME },
null, null, null);
try {
System.out.println(“c.getCount() :: ” + c.getCount());
if (c.getCount() > 0) {
c.moveToFirst();
displayName = c.getString(0);
ContactName = displayName;
}
else
{
ContactName = “UnknownPerson”;
}
System.out.println(“Display name=”+displayName);
System.
out.println(“Receiver ContactName :: ”
+ ContactName);
System.out.println(“str :: ” + str);
} catch (Exception e) {
e.printStackTrace();
} finally {
c.close();
}
}
}
}
}
in your manifest file :
<receiver android:name=”com.path.SmsReciever” >
<intent-filter>
<action android:name=”android.provider.Telephony.SMS_RECEIVED” >
</action>
</intent-filter>
</receiver>