Search code examples
androidbroadcastreceiver

delete incoming message from inbox in android


i want to delete incoming message from the inbox and just want to receive in my app i am trying this code but it is not working, i am using lollipop

public class SmsReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
       if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
            SmsMessage[] msgs = null;
            String msg_from = null;
            String msgBody = null;
            if (bundle != null){
                //---retrieve the SMS message received---
                try{
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];
                    for(int i=0; i<msgs.length; i++){
                        msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        msg_from = msgs[i].getOriginatingAddress();
                        msgBody = msgs[i].getMessageBody();
                    }
                }catch(Exception e){
                            Log.d("Exception caught", e.getMessage());
                }

                Toast.makeText(context, "Number : " +msg_from + "\n" + "Message : "+  msgBody , Toast.LENGTH_LONG).show();

                clearAbortBroadcast();
                this.abortBroadcast();

        }

    }
  }

}


Solution

  • First, make sure to set the highest priority possible to your receiver on the manifest file.

    Now, on KitKat and newer Android versions, you also have to make sure that your app is selected as the default SMS app and is listening to the SMS_DELIVER_ACTION. Not SMS_RECEIVED. Otherwise this won't work:

    On Android 4.4, only one app can receive the new SMS_DELIVER_ACTION intent, which the system broadcasts when a new SMS message arrives. (...) only the app that receives the SMS_DELIVER_ACTION broadcast (the user-specified default SMS app) is able to write to the SMS Provider.