Search code examples
androidsmsmanager

How to get the time of receiving of an sms


I am reading unread sms from a particular number by the following code .

public void getUnreadMessage() {
        Cursor smsInboxCursor1 = getContentResolver().query(
                Uri.parse("content://sms/inbox"), new String[] {},
                "read = 0 and address='" + pre_address + "'", null, null);
        int indexBody = smsInboxCursor1.getColumnIndex("body");
        int indexAddress = smsInboxCursor1.getColumnIndex("address");
        if (indexBody < 0 || !smsInboxCursor1.moveToFirst())
            return;
    //  arrayAdapter.clear();
        do {

            String str = "SMS From: " + smsInboxCursor1.getString(indexAddress)
                    + "\n" + smsInboxCursor1.getString(indexBody) + " \n";
            fromNumber = smsInboxCursor1.getString(indexAddress);
            smsBody.add(smsInboxCursor1.getString(indexBody));
            // arrayAdapter.add(str);
            status.add(false);

        } while (smsInboxCursor1.moveToNext());
    }

Now I want to get the time of receiving sms from this particular number . How can I do that ?


Solution

  • There is a column named DATE that contains the date the message was received. You can get directly like the other fields you already retrieve:

    int indexData = smsInboxCursor1.getColumnIndex("data");
    
    ...
    
    long dateReceived = smsInboxCursor1.getLong(indexData);
    

    Since it's a timestamp you need to convert in a human readable string. You can do it with this code:

    private String getDate(long time) {
        Calendar cal = Calendar.getInstance(Locale.ENGLISH);
        cal.setTimeInMillis(time);
        String date = DateFormat.format("dd-MM-yyyy HH:mm:ss", cal).toString();
        return date;
    }