Browse By

Android : Delete Message from Inbox programmatically in Android

Hi Android Developers…

Previously we have seen some articles based on SMS Messages:

  1. How to send SMS Message from Android Application
  2. Read SMS Message from Inbox / Sent / Draft in Android

If you are getting so many text messages on your android phone, and want to delete some Messages, today I will show you how to  Delete messages programmatically from Android Device.

From Android version 4.4, as per Google Policy only default application can delete message. If you wish to make your apps default then you need to develop complete SMS application and can make it default as per Google documentations.

To make your app default, you must implement all of the required capabilities:

a.) In a broadcast receiver, include an intent filter for SMS_DELIVER_ACTION (“android.provider.Telephony.SMS_DELIVER”). The broadcast receiver must also require the BROADCAST_SMS permission.

This allows your app to directly receive incoming SMS messages.

b.) In a broadcast receiver, include an intent filter for WAP_PUSH_DELIVER_ACTION (“android.provider.Telephony.WAP_PUSH_DELIVER”) with the MIME type “application/vnd.wap.mms-message”. The broadcast receiver must also require the BROADCAST_WAP_PUSH permission. This allows your app to directly receive incoming MMS messages.

c.) In your activity that delivers new messages, include an intent filter for ACTION_SENDTO (“android.intent.action.SENDTO”) with schema, sms:, smsto:, mms:, and mmsto:. This allows your app to receive intents from other apps that want to deliver a message.

d.) In a service, include an intent filter for ACTION_RESPONSE_VIA_MESSAGE (“android.intent.action.RESPOND_VIA_MESSAGE”) with schemas, sms:, smsto:, mms:, and mmsto:. This service must also require the SEND_RESPOND_VIA_MESSAGE permission.

Until all this permissions are not mentioned in manifest file, you can’t make your Sms App default. This article is for understanding purpose only. But if you are making your app default then your app is responsible for handling SMS and MMS and all features of messaging system.

Direct Download Full Source Code

Android : Delete Message from Inbox programmatically in Android

Lets go ahead and learn how to achieve this:

1. First of all we will add all this permissions in manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.vrs.smsapplicationdemo">
    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.WRITE_SMS" />
    <uses-permission android:name="android.permission.SEND_SMS"/>
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".SMSBReceiver" >
            <intent-filter android:priority="999" >
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
        <receiver android:name=".MmsReceiver"
            android:permission="android.permission.BROADCAST_SMS">
          <intent-filter>
                <action android:name="android.provider.Telephony.SMS_DELIVER" />
            </intent-filter>
        </receiver>
        <receiver android:name=".PushServiceReciever"
            android:enabled="@bool/is_kitkat"
            android:permission="android.permission.BROADCAST_WAP_PUSH">
            <intent-filter>
                <action android:name="android.provider.Telephony.WAP_PUSH_DELIVER" />
                <data android:mimeType="application/vnd.wap.mms-message" />
            </intent-filter>
        </receiver>
        <!-- Activity that allows the user to send new SMS/MMS messages -->
        <activity android:name=".SendSms" >
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <action android:name="android.intent.action.SENDTO" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="sms" />
                <data android:scheme="smsto" />
                <data android:scheme="mms" />
                <data android:scheme="mmsto" />
            </intent-filter>
        </activity>
        <!-- Service that delivers messages from the phone "quick response" -->
        <service android:name=".HeadlessSmsSendService"
            android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE"
            android:exported="true" >
            <intent-filter>
                <action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="sms" />
                <data android:scheme="smsto" />
                <data android:scheme="mms" />
                <data android:scheme="mmsto" />
            </intent-filter>
        </service>
    </application>
</manifest>

Here all mentioned classes, services and receivers should contain implementation for handling messages.

2. In res/values folder, mention the below value :

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="is_kitkat">true</bool>
</resources>

3. Open res/layout and modify “content_main.xml” file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.vrs.smsapplicationdemo.MainActivity"
    tools:showIn="@layout/activity_main">
   
 <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
       >
        <Button
            android:id="@+id/btnInbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:layout_weight="1"
            android:text="Inbox">
        </Button>
        <Button
            android:id="@+id/btnSentBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:layout_weight="1"
            android:text="Sent Box">
        </Button>
        <Button
            android:id="@+id/btnDraft"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:layout_weight="1"
            android:text="Draft">
        </Button>
        <Button
            android:id="@+id/btnSend"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:layout_weight="1"
            android:text="Compose">
        </Button>
    </LinearLayout>
    <ListView
        android:id="@+id/lvMsg"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@android:color/transparent"
       >
    </ListView>
</LinearLayout>

4. Now open “MainActivity.java”. To make your app default, you have to implement below code in onResume() method.

@Override
protected void onResume() {
    super.onResume();
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setMessage("This app is not set as your default messaging app. Do you want to set it as default?")
                    .setCancelable(false)
                    .setTitle("Alert!")
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @TargetApi(19)
                        public void onClick(DialogInterface dialog, int id) {
                            Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
                            intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
                            startActivity(intent);
                        }
                    });
            builder.show();
        }
    }
}
Alert from user side for default App

Alert from user side for default App Action

If user click on Yes then Android will give you warning regarding default SMS App change.

This slideshow requires JavaScript.

If user denies any of the permission then App will not act as default App, and you will not able to delete SMS Messages.

5. Create method in “MainActivity.java” to fetch messages of inbox. For more details, refer our article Read SMS Message from Inbox / Sent / Draft in Android App.

private void fetchInbox() {
    Uri inboxURI = Uri.parse("content://sms/inbox");
    String[] reqCols = new String[]{"_id", "address", "body"};
    ContentResolver cr = getContentResolver();
    Cursor c = cr.query(inboxURI, reqCols, null, null, null);
    adapter = new SimpleCursorAdapter(this, R.layout.row, c,
            new String[]{"body", "address"}, new int[]{
            R.id.lblMsg, R.id.lblNumber}, 0);
    lvMsg.setAdapter(adapter);
    lvMsg.setOnItemLongClickListener(this);
}

6. Now Handle the click event of listview in “Mainactivity.class”. Here we will delete messages of inbox by passing the id of selected message.

@Override
public boolean onItemLongClick(AdapterView<?> parent, final View view, final int position, long id) {
    final Cursor c = (Cursor) adapter.getItem(position);
    final long cid = c.getLong(c.getColumnIndex("_id"));
    String message = c.getString(c.getColumnIndex("body"));
    String number = c.getString(c.getColumnIndex("address"));
    Log.e("id", cid + "");
    Log.e("message label", number + "");
    Log.e("message body", message + "");
    AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
    alert.setMessage(" Are you sure you want to delete this message?");
    alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            deleteSMS(MainActivity.this, cid);
            fetchInbox();
        }
    });
    alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    alert.create();
    alert.show();
    return false;
}

7. Now execute App.

This slideshow requires JavaScript.

I hope you like this article. Share your views to to improve content. Please stay tune with us. Happy Coding !!!

Subscribe for more articles!!

Download Full Source Code

  • Pingback: How to send SMS Message in Android - Pulse7()

  • Tushar Shah

    i have a lolipop phone im unable to get this part
    Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
    intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
    startActivity(intent);

  • vihar maravaniya

    ffgffgf

  • vihar maravaniya

    why i cant download source code ??

    i was liked and shared on G+… also