user2229896
user2229896

Reputation: 71

Delete sms android after receiving With no delay

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.

Upvotes: 7

Views: 3122

Answers (2)

Ahmad
Ahmad

Reputation: 1

You must delete sms with Smsid

getContentResolver().delete(Uri.parse("content://sms/" + smsid), null, null);

Upvotes: 0

Ayush
Ayush

Reputation: 3999

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

Upvotes: 5

Related Questions