Read all SMS from a particular sender - android

How do I read all SMSes from a particular sender to me? E.g. I want to scan a) the body, and b) the date/time of all SMSes that came from 'TM-MYAMEX' to the phone.
Some websites seem to indicate this can be read from "content://sms/inbox". I couldn't figure out exactly how. Also not sure if it is supported on most phones. I am using a Galaxy S2.

try this way:
StringBuilder smsBuilder = new StringBuilder();
final String SMS_URI_INBOX = "content://sms/inbox";
final String SMS_URI_ALL = "content://sms/";
try {
Uri uri = Uri.parse(SMS_URI_INBOX);
String[] projection = new String[] { "_id", "address", "person", "body", "date", "type" };
Cursor cur = getContentResolver().query(uri, projection, "address='123456789'", null, "date desc");
if (cur.moveToFirst()) {
int index_Address = cur.getColumnIndex("address");
int index_Person = cur.getColumnIndex("person");
int index_Body = cur.getColumnIndex("body");
int index_Date = cur.getColumnIndex("date");
int index_Type = cur.getColumnIndex("type");
do {
String strAddress = cur.getString(index_Address);
int intPerson = cur.getInt(index_Person);
String strbody = cur.getString(index_Body);
long longDate = cur.getLong(index_Date);
int int_Type = cur.getInt(index_Type);
smsBuilder.append("[ ");
smsBuilder.append(strAddress + ", ");
smsBuilder.append(intPerson + ", ");
smsBuilder.append(strbody + ", ");
smsBuilder.append(longDate + ", ");
smsBuilder.append(int_Type);
smsBuilder.append(" ]\n\n");
} while (cur.moveToNext());
if (!cur.isClosed()) {
cur.close();
cur = null;
}
} else {
smsBuilder.append("no result!");
} // end if
}
} catch (SQLiteException ex) {
Log.d("SQLiteException", ex.getMessage());
}
AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_SMS" />

try this, its a easy way for reading message from inbox.
public class ReadMsg extends AppCompatActivity {
ListView listView;
private static final int PERMISSION_REQUEST_READ_CONTACTS = 100;
ArrayList smsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_msg);
listView = (ListView)findViewById(R.id.idList);
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
if (permissionCheck == PackageManager.PERMISSION_GRANTED){
showContacts();
}else{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS},PERMISSION_REQUEST_READ_CONTACTS);
}
}
private void showContacts() {
Uri inboxURI = Uri.parse("content://sms/inbox");
smsList = new ArrayList();
ContentResolver cr = getContentResolver();
Cursor c = cr.query(inboxURI,null,null,null,null);
while (c.moveToNext()){
String Number = c.getString(c.getColumnIndexOrThrow("address")).toString();
String Body= c.getString(c.getColumnIndexOrThrow("body")).toString();
smsList.add("Number: "+ Number + "\n" + "Body: "+ Body );
}
c.close();
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, smsList);
listView.setAdapter(adapter);
}
}
Add this permission into Manifests.
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inbox = (Button) findViewById(R.id.inbox);
list = (ListView) findViewById(R.id.list);
arlist = new ArrayList<String>();
inbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri inboxUri = Uri.parse("content://sms/inbox");
String[] reqCols = {"_id", "body", "address"};
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(inboxUri, reqCols, "address='+919456'", null, null);
adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.msg_content_layout, cursor,
new String[]{"body", "address"}, new int[]{R.id.txt1, R.id.txt2});
list.setAdapter(adapter);
}
});
}
Here I have added the number +919456 as the value of the address field.
Apart from this you need to add the READ_SMS permission to manifest:

you can do this in few line of code
String[] phoneNumber = new String[] { "+923329593103" };
Cursor cursor1 = getContentResolver().query(Uri.parse("content://sms/inbox"), new String[] { "_id", "thread_id", "address", "person", "date","body", "type" }, "address=?", phoneNumber, null);
StringBuffer msgData = new StringBuffer();
if (cursor1.moveToFirst()) {
do {
for(int idx=0;idx<cursor1.getColumnCount();idx++)
{
msgData.append(" " + cursor1.getColumnName(idx) + ":" + cursor1.getString(idx));
}
} while (cursor1.moveToNext());
} else {
edtmessagebody.setText("no message from this contact"+phoneNumber);
}

public class SmsController extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
SmsMessage msgs[] = null;
Bundle bundle = intent.getExtras();
try {
Object pdus[] = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int n = 0; n < pdus.length; n++) {
byte[] byteData = (byte[]) pdus[n];
msgs[n] = SmsMessage.createFromPdu(byteData);
}
} catch (Exception e) {
}
for (int i = 0; i < msgs.length; i++) {
String message = msgs[i].getDisplayMessageBody();
if (message != null && message.length() > 0) {
String from = msgs[i].getOriginatingAddress();
if(FROM.contains("TM-MYAMEX")){
String body = message ;
Date datetime = new Date() ;
}
}
}
}
}
}
I'm not sure of what does "TM-MYAMEX" means but here is the code to get all SMS.
Date = new Date()beacause its under a BroadcastReceiverthen the tme you get the message its the current time.
Hope this help.

Related

Reading sms from android inbox who's sender doesn't have a number

I am making an app which records the messages from a particular sender.For e.g I want to get all SMS from the bank HDFC in a Listview.The sender's address in my inbox is named as "AM-HDFC".I have tried the below code but the app crashes saying that URI is not found.What will be the possible solution?
public class MsgReader extends AppCompatActivity {
Cursor c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_msg_reader);
List<Sms> smslist=getAllSms("inbox");
RecyclerView rView = (RecyclerView) findViewById(R.id.list);
rView.setLayoutManager(new LinearLayoutManager(this));
rView.setHasFixedSize(true);
MsgAdapter rcAdapter = new MsgAdapter(smslist);
rView.setAdapter(rcAdapter);
}
public List<Sms> getAllSms(String folderName) {
List<Sms> lstSms = new ArrayList<Sms>();
Sms objSms = new Sms();
Uri message = Uri.parse("content://sms/");
ContentResolver cr = this.getContentResolver();
c= cr.query(Uri.parse("content://mms-sms/AM-HDFC"), null, null, null, null);
this.startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
objSms = new Sms();
objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
objSms.setAddress(c.getString(c.getColumnIndexOrThrow("address")));
objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
objSms.setReadState(c.getString(c.getColumnIndex("read")));
objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
lstSms.add(objSms);
c.moveToNext();
}
}
else {
throw new RuntimeException("You have no SMS in " + folderName);
}
c.close();
return lstSms;
}
#Override
protected void onPause() {
super.onPause();
if (c != null) {
c.close();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (c != null) {
c.close();
}
}
}
Try this :
public void getSmsInbox(Context context, String address) {
String selection = Telephony.Sms.ADDRESS+"='"+address+"'";
ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(Telephony.Sms.CONTENT_URI, null, selection, null, null);
if (c != null) {
if (c.moveToFirst()) {
for (int j = 0; j < c.getCount() ; j++) {
String smsDate = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.DATE));
Date dateFormat = new Date(Long.valueOf(smsDate));
String body = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.BODY));
Log.d(TAG, address+", "+dateFormat.toString()+" : "+body);
c.moveToNext();
}
}
c.close();
} else {
Toast.makeText(this, "No message to show!", Toast.LENGTH_SHORT).show();
}
}
Use it like this :
getSmsInbox(MainActivity.this, "AM-HDFC");
And don't forget to ask for the permission :
<uses-permission android:name="android.permission.READ_SMS" />

Delete number from contacts

The following code lets me display duplicate contacts.
And when I try to delete, it deletes the duplicated number as well as the original number.
I want it to delete only the duplicated number present in the listview.
Here is my code.
public class MainActivity extends Activity {
ListView listView;
ArrayList<String> listItems = new ArrayList<String>();
Set<String> dupesRemoved = new HashSet<String>();
String[] newList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor curLog = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,order);
Cursor cursor = null;
if(curLog != null) {
while(curLog.moveToNext()) {
String str = curLog.getString(curLog.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
//contactid = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
listItems.add(str);
}
}
dupesRemoved = findDuplicates(listItems);
String listString = dupesRemoved.toString();
listString = listString.substring(1,listString.length()-1);
newList = listString.split(", ");
//Arrays.sort(newList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, newList);
listView.setAdapter(adapter);
}
public void deleteDupes(View view) {
String[] info = new String[2];
for (String s : newList) {
info = (getContactInfo(s));
updateContact(info[0],this,info[1]);
listView.invalidateViews();
}
}
public void updateContact(String contactId, Activity act, String type){
/* ASSERT: #contactId alreay has a work phone number */
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String selectPhone = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" +
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'" + " AND " + ContactsContract.CommonDataKinds.Phone.TYPE + "=?";
String[] phoneArgs = new String[]{contactId,type /*String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)*/};
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs).build());
try {
act.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
public static Set<String> findDuplicates(List<String> listContainingDuplicates) {
final Set<String> setToReturn = new HashSet<String>();
final Set<String> set1 = new HashSet<String>();
for (String yourInt : listContainingDuplicates) {
if (!set1.add(yourInt)) {
setToReturn.add(yourInt);
}
}
return setToReturn;
}
private String[] getContactInfo(String number)
{
String[] contactInfo = new String[2];
ContentResolver context = getContentResolver();
/// number is the phone number
Uri lookupUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
String[] mPhoneNumberProjection = { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup.TYPE };
Cursor cur = context.query(lookupUri,mPhoneNumberProjection, null, null, null);
try
{
if (cur.moveToFirst())
{
contactInfo[0] = cur.getString(0);
contactInfo[1] = cur.getString(2);
return contactInfo;
}
}
finally
{
if (cur != null)
cur.close();
}
return contactInfo;
}
}
Use hashmap instead of arraylist to store items in key value pair as duplicate keys are not allowed in a map.
Java code for delete contact:
public static boolean deleteContact(Context ctx, String phone, String name) {
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
try {
if (cur.moveToFirst()) {
do {
if (cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
ctx.getContentResolver().delete(uri, null, null);
return true;
}
} while (cur.moveToNext());
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
}
return false;
}
Manifest permission:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />

how to remove duplicate contacts from arraylist

I have created an app in which I am getting the contacts from a device.
But I want to remove the duplicate contacts from the results.
How could I do it?
MainActivity
public class MainActivity extends Activity implements OnItemClickListener {
EditText searchText;
ArrayList<String> phno0 = new ArrayList<String>();
List<String> arrayListNames;
public List<ProfileBean> list;
public SearchableAdapter adapter;
//ProfileBean bean;
String[] cellArray = null;
String contacts;
ListView lv;
String phoneNumber, name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
lv = (ListView) findViewById(R.id.listview);
list = new ArrayList<ProfileBean>();
getAllCallLogs(this.getContentResolver());
adapter = new SearchableAdapter(getApplication(), list);
lv.setAdapter(adapter);
lv.setItemsCanFocus(false);
lv.setOnItemClickListener(this);
lv.setTextFilterEnabled(true);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
while (phones.moveToNext()) {
phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
list.add(new ProfileBean(name, phoneNumber));
}
phones.close();
}
}
If you want to get rid of duplicates, consider using a HashSet instead.
If you can't/don't want to use it, simply check before adding whether the contact is already there.
if (!myList.contains(newContact))
myList.add(newContact);
Add the following checking in the place of list.add(new ProfileBean(name, phoneNumber)); before adding into list:
int flag = 0
if(list.size() == 0){
list.add(new ProfileBean(name, phoneNumber));
}
for(int i=0;i<list.size();i++){
if(!list.get(i).getProfileName().trim().equals(name)){
flag = 1;
}else{
flag =0;
break;
}
}
if(flag == 1){
list.add(new ProfileBean(name, phoneNumber));
}
The following function can be used for removing duplicates from String ArrayList Change it according to your requirement
public ArrayList<String> listWithoutDuplicates(ArrayList<String> duplicateList) {
// Converting ArrayList to HashSet to remove duplicates
LinkedHashSet<String> listToSet = new LinkedHashSet<String>(duplicateList);
// Creating Arraylist without duplicate values
ArrayList<String> listWithoutDuplicates = new ArrayList<String>(listToSet);
return listWithoutDuplicates;
}
use below code list=removeDuplicates(list);
public List<ProfileBean> removeDuplicates(List<ProfileBean> list) {
// Set set1 = new LinkedHashSet(list);
Set set = new TreeSet(new Comparator() {
#Override
public int compare(Object o1, Object o2) {
if (((ProfileBean) o1).getName().equalsIgnoreCase(((ProfileBean) o2).getName()) &&
((ProfileBean)o1).getPhoneNumber().equalsIgnoreCase(((ProfileBean)o2).getPhoneNumber())) {
return 0;
}
return 1;
}
});
set.addAll(list);
final List newList = new ArrayList(set);
return newList;
}
Try to get ContactsContract.Contacts.NAME_RAW_CONTACT_ID) its unique id and its used for update contacts compare your contacts with raw id is same or not as below
private void getAllContactsBackground() {
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor cursorInfo = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getActivity().getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id));
Uri pURI = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Bitmap photo = null;
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
}
while (cursorInfo.moveToNext()) {
ContactsModel info = new ContactsModel();
info.contacts_id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
info.contacts_raw_id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.NAME_RAW_CONTACT_ID));
info.contacts_name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
info.contacts_mobile = cursorInfo.getString(cursorInfo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceFirst("[^0-9]" + "91", "");
info.contacts_photo = photo;
info.contacts_photoURI = String.valueOf(pURI);
Cursor emailCur = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
info.contacts_email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("email==>", "" + info.contacts_email);
}
emailCur.close();
int flag = 0;
if (arrayListAllContacts.size() == 0) {
arrayListAllContacts.add(info);
}
for (int i = 0; i < arrayListAllContacts.size(); i++) {
if (!arrayListAllContacts.get(i).getContacts_raw_id().trim().equals(info.contacts_raw_id)) {
flag = 1;
} else {
flag = 0;
break;
}
}
if (flag == 1) {
arrayListAllContacts.add(info);
}
}
cursorInfo.close();
}
}
cursor.close();
}
}

Is there any solution to load phone messages in an activity?

I'd like to load messages from phone in my activity. I search for solution, but I can`t find any.
Use this :
private String SmsDetails(Application mContext) {
// TODO Auto-generated method stub
smsInbox = new ArrayList<Entry>();
final Uri SMS_Inbox = Uri.parse("content://sms/inbox");
String smsHistory = "";
try {
String sDirection = "1";
String sMessageType = "0";
String SMS_READ_COLUMN = "read";
String SORT_ORDER = " _id ASC";
int count = 0;
Cursor cursor;
int iLastIDRun = 0;
// "address = '+9180009'"
cursor = mContext.getContentResolver().query(
SMS_Inbox,
new String[] { "_id", "thread_id", "address", "person",
"date", "body" },
" _id > " + String.valueOf(iLastIDRun), null,
SORT_ORDER);
sMessageType = "1";
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
do {
String address = cursor.getString(2);
long timestamp = cursor.getLong(4);
String sBody = cursor.getString(5);
if (address.startsWith("1")) {
address = address.substring(1);
}
//store the required details
} while (cursor.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
}
cursor.close();
}
doCheckSmsHistory();
} catch (Exception e) {
e.printStackTrace();
}
return smsHistory;
}

Load Sms from inbox for specific number

I have implemented the code to get sms from inbox to my app.It gets all messages.But I want to load messages from specific number.I followed the tutorial from [Read all SMS from a particular sender it shows empty view.I worked out this code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inbox);
ListView list = (ListView) findViewById(R.id.listView1);
List<String> msgList = getSMS();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, msgList);
list.setAdapter(adapter);
}
public List<String> getSMS() {
List<String> sms = new ArrayList<String>();
// StringBuilder smsBuilder = new StringBuilder();
final String SMS_URI_INBOX = "content://sms/inbox";
final String SMS_URI_ALL = "content://sms/";
try {
Uri uri = Uri.parse(SMS_URI_INBOX);
String[] projection = new String[] { "_id", "address", "person", "body", "date", "type" };
Cursor cur = getContentResolver().query(uri, projection, "address='5558'", null, null);
if (cur.moveToFirst()) {
int index_Address = cur.getColumnIndex("address");
int index_Person = cur.getColumnIndex("person");
int index_Body = cur.getColumnIndex("body");
int index_Date = cur.getColumnIndex("date");
int index_Type = cur.getColumnIndex("type");
do {
String strAddress = cur.getString(index_Address);
int intPerson = cur.getInt(index_Person);
String strbody = cur.getString(index_Body);
long longDate = cur.getLong(index_Date);
int int_Type = cur.getInt(index_Type);
sms.add("Number: " + strAddress + " .Message: " + strbody);
// smsBuilder.append("[ ");
// smsBuilder.append(strAddress + ", ");
// smsBuilder.append(intPerson + ", ");
// smsBuilder.append(strbody + ", ");
// smsBuilder.append(longDate + ", ");
//smsBuilder.append(int_Type);
// smsBuilder.append(" ]\n\n");
} while (cur.moveToNext());
if (!cur.isClosed()) {
cur.close();
cur = null;
}
else {
// smsBuilder.append("no result!");
} // end if
}} catch (SQLiteException ex) {
Log.d("SQLiteException", ex.getMessage());
}
return sms;
}
I passed address as my another emulator.If I gave null replacing address field of getContentResolver()it will load all sms in inbox.Can anyone help me where I have to modify ?
Use following code,
Uri uri = Uri.parse("content://sms/");
ContentResolver contentResolver = getContentResolver();
String phoneNumber = "+911234567890";
String sms = "address='"+ phoneNumber + "'";
Cursor cursor = contentResolver.query(uri, new String[] { "_id", "body" }, sms, null, null);
System.out.println ( cursor.getCount() );
while (cursor.moveToNext())
{
String strbody = cursor.getString( cursor.getColumnIndex("body") );
System.out.println ( strbody );
}
Following permission is required,
<uses-permission android:name="android.permission.READ_SMS"/>
100% working code :
String[] projection = new String[] { "_id", "thread_id","address", "person", "body", "date", "type" };
Uri uri = Uri.parse("content://sms/");
Cursor c = cr.query(uri, projection,"address='9876543210'",null, "date desc");
int totalSMS = 0;
if (c != null) {
totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int j = 0; j < totalSMS; j++) {
String id = c.getString(c.getColumnIndexOrThrow(Telephony.Sms._ID));
String thread_id = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.THREAD_ID));
String smsDate = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.DATE));
String number = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.ADDRESS));
String body = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.BODY));
String type;
switch (Integer.parseInt(c.getString(c.getColumnIndexOrThrow(Telephony.Sms.TYPE)))) {
case Telephony.Sms.MESSAGE_TYPE_INBOX:
type = "inbox";
messageList.add(new Message(id, thread_id, number, body, smsDate, type));
break;
case Telephony.Sms.MESSAGE_TYPE_SENT:
type = "sent";
messageList.add(new Message(id, thread_id, number, body, smsDate, type));
break;
case Telephony.Sms.MESSAGE_TYPE_OUTBOX:
break;
default:
break;
}
c.moveToNext();
}
}
c.close();

Categories

Resources