Marking SMS as read on Android not working - android

I'm trying to mark a message as read on a Samsung Galaxy S6 and it is not working. I have following tutorials online. My code is below:
Uri uri = Uri.parse("content://sms/inbox");
Cursor cursor = context.getContentResolver().query(uri, null, "_id=" + id, null, null);
try {
if (cursor.getCount() != 0) {
ContentValues values = new ContentValues();
values.put("read", true);
context.getContentResolver().update(uri, values, "_id=?", new String[] { id });
}
} catch (Exception e) {
Log.e("Mark Read", "Error in Read: " + e.toString());
} finally {
cursor.close();
}
Is there something i'm doing wrong? I pass in a id to this method and the message is always marked as unread. How is it that other SMS applications can mark as read and I cannot?

Turns out you cannot mark SMS messages as read if you are NOT the default SMS client. Lame!

Related

Android content provider query not retrieving updated information

So I've written a query to extract the WhatsApp contacts of a phone. My initial query goes like this:
Cursor c = con.getContentResolver().query(
ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts.CONTACT_ID, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY},
ContactsContract.RawContacts.ACCOUNT_TYPE + "= ?",
new String[]{"com.whatsapp"},
null
);
ArrayList<String> myWhatsappContacts = new ArrayList<String>();
int contactNameColumn = c.getColumnIndex(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY);
while (c.moveToNext()) {
// You can also read RawContacts.CONTACT_ID to read the
// ContactsContract.Contacts table or any of the other related ones.
myWhatsappContacts.add(c.getString(contactNameColumn));
}
The purpose of this is to find out how many WhatsApp contacts the phone has at any one time. When I do:
Log.i("WhatsApp contacts found:", Integer.toString(myWhatsappContacts.size());
It should print out how many WhatsApp contacts there were into LogCat. And this works - up to a point.
Let's say for example that the number of WhatsApp contacts I have now is 101. The next phase of this little project is to delete away ALL contacts if there are more than 100 of them. In which case, we go:
if (myWhatsappContacts.size() > 100) {
//Delete all contacts code here
}
I've tested the delete contacts code, it works. I check the contacts directory of the phone via the contacts app, and it says 0. But now when I do the query again (refer to code above), it still shows 101! What's going on?
If it helps, my DeleteContacts method is as follows:
private void deleteContact(Context ctx, String phone, String name) {
Uri contactUri = Uri.withAppendedPath(ContactsContract.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(ContactsContract.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;
}
} while (cur.moveToNext());
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
} finally {
cur.close();
}
return;
}
What am I doing wrong? Is my DeleteContacts code faulty? Or is the query itself faulty?

Mark incoming SMS as Read in Default SMS Application

Sorry if i did not come up with a suitable title.
I want to know that is it possible to mark SMS as read in the default SMS Application through my Application?
i.e. i am developing my own application in which i am storing sms that are not from the contact list but the problem is that when ever sms received it received on my app and also on the default sms app so i want that when ever sms received then i can mark the sms as read(of the default SMS App) so that there is no need for go to default sms app and mark SMS as read.
Can i do that from my Application?
try this code
private void markMessageASRead(Context context, String numb, String body) {
Uri uri = Uri.parse("content://sms/inbox");
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
try{
while (cursor.moveToNext()) {
if ((cursor.getString(cursor.getColumnIndex("address")).equals(number)) && (cursor.getInt(cursor.getColumnIndex("read")) == 0)) {
if (cursor.getString(cursor.getColumnIndex("body")).startsWith(body)) {
String SmsMessageId = cursor.getString(cursor.getColumnIndex("_id"));
ContentValues values = new ContentValues();
values.put("read", true);
context.getContentResolver().update(Uri.parse("content://sms/inbox"), values, "_id=" + SmsMessageId, null);
return;
}
}
}
}catch(Exception e)
{
Log.e("Mark Read", "Error in Read: "+e.toString());
}
}

Get full conversation with Android query

I would like to get all messages from one contact. I have the contact ID _id, so I've already do something like this :
private void displayMessages() {
ContentResolver cr = this.getContentResolver();
try {
Cursor cursor = cr.query(Uri.parse("content://mms-sms/conversations"), new String[]{"*"}, this.contID + "= _id" , null, null); //contID is the unique ID for one contact in our android.
while (cursor.moveToNext()) {
System.out.println("Number: " + cursor.getString(cursor.getColumnIndexOrThrow("address")));
System.out.println("Body : " + cursor.getString(cursor.getColumnIndexOrThrow("body")));
}
cursor.close();
}
catch (Exception e) {
System.out.print("ERROR");
}
I've asked something like
SELECT * FROM content://mms-sms/conversations WHERE _id = contID
As you can see, in my query, I ask system for messages from one contact (user id that I know) But I can just display the last message body. So I think it exists others query to get all messages from one user ?
Any ideas ???
I doubt that _id in this case is the id of the contact you are sending sms/mms to but rather the thread's id. The column you probably want to use for your query clause is RECIPIENT_IDS. For debugging purpose try without the where clause and dump the cursor to analyze the results
Cursor cursor = cr.query(Uri.parse("content://mms-sms/conversations"), new String[]{"*"}, null , null, null);
DatabaseUtils.dumpCursor(cursor);
Sorry for answer too late, but I've found a solution.
Here is my code :
private void displayMessages() {
ContentResolver cr = this.getContentResolver();
boolean isMe;
try {
Cursor cursor = cr.query(Uri.parse("content://sms"), null, this.cont.getThread_ID() + " = thread_id" , null, "date ASC");
while (cursor.moveToNext()) {
//if it's a received message :
if ((cursor.getString(cursor.getColumnIndexOrThrow("person")) != null)) {
isMe = false;
}
else {
//it's a message sent by me.
isMe = true;
}
date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
System.out.println("Number: " + cursor.getString(cursor.getColumnIndexOrThrow("address")));
System.out.println("Body : " + cursor.getString(cursor.getColumnIndexOrThrow("body") + "\n");
}
cursor.close();
}
Thanks to "conent://sms" table, I can get all sms !
So I've used thread_id to display all messages, and thanks to the person column, I can know if the message was sent by me or my contact.

Unable to delete SMS programmatically

I have tried variations on deleting all or some messages from the SMS, including but not limited to thread id, id, where clause, etc.
Android manifest reflects read and write permissions.
I tried with variations on the SMS content, from inbox etc.
Nothing seems to delete the record.
Here is the last iteration:
Cursor c = getApplicationContext().getContentResolver().query(Uri.parse("content://sms/"), null, null, null,null);
try {
while (c.moveToNext()) {
int Id = c.getInt(0);
String pid = c.getString(0);
// String uri = "content://sms/conversations/" + threadId;
String strUriAll = "content://sms/" + pid;//SMS_ALL
Log.d("URI is ", strUriAll);
getApplicationContext().getContentResolver().delete(Uri.parse(strUriAll), null, null);
// getApplicationContext().getContentResolver().delete(Uri.parse(strUriAll), null, null);
}
}catch(Exception e){
Log.e(this.toString(),"Error deleting sms",e);
}finally {
c.close();
}
Android 4.4 Kitkat introduced changes in SMS handling where now only the default SMS app is allowed write access to the SMS database - all other apps silently fail when attempting to write.

Deleting Android SMS programmatically

I want to delete some certain SMS automatically in my Android application. Therefore I have a method which does exactly what I want it to do. However, it only works if I deploy the application directly to my phone from Eclipse. Then it deletes incoming SMS. However, it does not work if the application is downloaded from the market. But there is also no error. Does anybody know how I can solve this or does this only work on rooted devices?
public void deleteSMS(Context context, String message, String number) {
try {
mLogger.logInfo("Deleting SMS from inbox");
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = context.getContentResolver().query(uriSms,
new String[] { "_id", "thread_id", "address",
"person", "date", "body" }, null, null, null);
if (c != null && c.moveToFirst()) {
do {
long id = c.getLong(0);
long threadId = c.getLong(1);
String address = c.getString(2);
String body = c.getString(5);
if (message.equals(body) && address.equals(number)) {
mLogger.logInfo("Deleting SMS with id: " + threadId);
context.getContentResolver().delete(
Uri.parse("content://sms/" + id), null, null);
}
} while (c.moveToNext());
}
} catch (Exception e) {
mLogger.logError("Could not delete SMS from inbox: " + e.getMessage());
}
}
Actually, the code in my post is 100% correct. The problem was that Android needs some time to store the SMS upon receiving it. So the solution is to just add a handler and delay the delete request for 1 or 2 seconds.
This actually solved the whole issue.
EDIT (thanks to Maksim Dmitriev):
Please consider that you can't delete SMS messages on devices with Android 4.4.
Also, the system now allows only the default app to write message data to the provider, although other apps can read at any time.
http://developer.android.com/about/versions/kitkat.html
No exception will be thrown if you try; nothing will be deleted. I have just tested it on two emulators.
How to send SMS messages programmatically
Please consider that you can't delete SMS messages on devices with Android 4.4.
Also, the system now allows only the default app to write message data
to the provider, although other apps can read at any time.
http://developer.android.com/about/versions/kitkat.html
No exception will be thrown if you try; nothing will be deleted. I have just tested it on two emulators.
How to send SMS messages programmatically
hey use this code to delete customize sms
1. By date
2. By number
3. By body
try {
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = context.getContentResolver().query(
uriSms,
new String[] { "_id", "thread_id", "address", "person",
"date", "body" }, "read=0", null, null);
if (c != null && c.moveToFirst()) {
do {
long id = c.getLong(0);
long threadId = c.getLong(1);
String address = c.getString(2);
String body = c.getString(5);
String date = c.getString(3);
Log.e("log>>>",
"0--->" + c.getString(0) + "1---->" + c.getString(1)
+ "2---->" + c.getString(2) + "3--->"
+ c.getString(3) + "4----->" + c.getString(4)
+ "5---->" + c.getString(5));
Log.e("log>>>", "date" + c.getString(0));
ContentValues values = new ContentValues();
values.put("read", true);
getContentResolver().update(Uri.parse("content://sms/"),
values, "_id=" + id, null);
if (message.equals(body) && address.equals(number)) {
// mLogger.logInfo("Deleting SMS with id: " + threadId);
context.getContentResolver().delete(
Uri.parse("content://sms/" + id), "date=?",
new String[] { c.getString(4) });
Log.e("log>>>", "Delete success.........");
}
} while (c.moveToNext());
}
} catch (Exception e) {
Log.e("log>>>", e.toString());
}
You can choose which app is the default SMS app in 4.4+ and if your app is set as the default it will be able to delete SMS as well.
to make app as default app see this.
Check if your app is default sms app before deleting.
Use the URI provided by telephony class instead of hardcoding.
public void deleteSMS(Context context,int position)
{
Uri deleteUri = Uri.parse(Telephony.Sms.CONTENT_URI);
int count = 0;
Cursor c = context.getContentResolver().query(deleteUri, new String[]{BaseColumns._ID}, null,
null, null); // only query _ID and not everything
try {
while (c.moveToNext()) {
// Delete the SMS
String pid = c.getString(Telephony.Sms._ID); // Get _id;
String uri = Telephony.Sms.CONTENT_URI.buildUpon().appendPath(pid)
count = context.getContentResolver().delete(uri,
null, null);
}
} catch (Exception e) {
}finally{
if(c!=null) c.close() // don't forget to close the cursor
}
}
it delete all(inbox,outbox,draft) the SMS.
private int deleteMessage(Context context, SmsMessage msg) {
Uri deleteUri = Uri.parse("content://sms");
int count = 0;
#SuppressLint("Recycle") Cursor c = context.getContentResolver().query(deleteUri, null, null, null, null);
while (c.moveToNext()) {
try {
// Delete the SMS
String pid = c.getString(0); // Get id;
String uri = "content://sms/" + pid;
count = context.getContentResolver().delete(Uri.parse(uri),
null, null);
} catch (Exception e) {
}
}
return count;
}
use this code.............
or
getContentResolver().delete(Uri.parse("content://sms/conversations/" + threadIdIn), null, null);
I was looking for a method to delete all SMS with one click. Thanks to this post I succeeded.
Here is my method if it interests someone :
private void deleteSMS(){
Uri myUri= Uri.parse("content://sms/");
Cursor cursor = getContext().getContentResolver().query(myUri, null,null,null,null);
while (cursor.moveToNext()) {
int thread_id = cursor.getInt(1);
getContext().getContentResolver().delete(Uri.parse("content://sms/conversations/" + thread_id),null,null);
}
cursor.close();
}
if you want get a message and your sms app your android device phone didn't send any notification use Binary (Data) SMS.

Categories

Resources