Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete sms android after receiving With no delay

Tags:

android

sms

I have some code to delete Android SMS messages programatically but when I try to delete it in onReceive then no SMS is deleted.

Sample code to delete sms

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());
}

When I paste this in onReceived then the new SMS is not deleted.

like image 905
user2229896 Avatar asked Mar 31 '13 18:03

user2229896


People also ask

Can we delete an SMS in Android before it reaches the inbox?

@kakopappa: Yes, as mentioned in the answer it works from Android 1.6+.


1 Answers

You need to add permissions to your manifest file and increase priority of your SMS Receiver class

<receiver android:name=".SMSReceiver" > 
    <intent-filter android:priority="1000"> 
        <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
    </intent-filter> 
</receiver>

This is because it will call the SMSReceiver before any OS level operations like(Saving SMS, notification, SMS Sound And so on.).

Then in SMSReceiver onReceive() you need to add abortBroadcast() to abort any further Broadcasts

public void onReceive(Context context, Intent intent) {
  abortBroadcast();
}

that's all

cheers

Ayush Shah

like image 181
Ayush Avatar answered Sep 20 '22 11:09

Ayush