Monday, 2 January 2012

Delete Message from Message Box in android

Description:


Below method will delete message/s from Message box between two dates, depends upon passed argument.


Required Permissions.: <uses-permission android:name="android.permission.READ_SMS"/>
                          <uses-permission android:name="android.permission.WRITE_SMS"/>


 Uri uri = Uri.parse("content://sms/inbox");//Delete only inbox message
//Uri uri = Uri.parse("content://sms/sent");//Delete only sent message
//Uri uri = Uri.parse("content://sms/draft");//Delete only draft message
String dateFormat="dd-MM-yyyy";//You can change date format as per your requirement.
    /**
     * Delete  sms from Message box between two dates
     * @param  Uri  Content uri for sent/inbox/draft sms
     *
     * @param from=  date from which day
     * @param to= To which day message
     */

    protected boolean deletMsgFromMessageBox(Uri uri,String fromDate, String toDate,Context mContext) {
        try {
            Uri uriSms = uri;
            Calendar calCurr = Calendar.getInstance();
            Calendar calFrom = Calendar.getInstance();
            Calendar calto = Calendar.getInstance();

            calFrom.setTime((Date) new SimpleDateFormat(dateFormat)
                    .parse(fromDate));
            calto.setTime((Date) new SimpleDateFormat(dateFormat).parse(toDate));

            

            Cursor c = mContext.getContentResolver().query(uriSms, nullnull,
                    nullnull);

            int co = 0;
            while (c.moveToNext()) {
                calCurr.setTime((Date) new SimpleDateFormat(dateFormat)
                        .parse(getDateFromCursor(c)));
                co++;

                if (calCurr.after(calFrom) && calCurr.before(calto)) {

                    int id = c.getInt(0);
                    int thread_id = c.getInt(1); // get the thread_id
                    mContext.getContentResolver().delete(
                            Uri.parse("content://sms/conversations/"
                                    + thread_id),
                            "thread_id=? and _id=?",
                            new String[] { String.valueOf(thread_id),
                                    String.valueOf(id) });
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

7 comments:

  1. Thank you for posting such a useful code
    I am trying to implement it
    put I am getting an error saying that I have to define the function (getDateFromCursor(c)).

    ReplyDelete
  2. The method getDateFromCursor(Cursor) is undefined for the type Context

    ReplyDelete
  3. delete code is not working..

    ReplyDelete

  4. Send pre-recorded voice through bulk Voice SMS software, Voice SMS mobile app or via voice Bulk SMS API in single click.

    ReplyDelete
  5. plz help mw i am testing on oreo version

    ReplyDelete